You are here: Home > Articles > Article Display

Creating and consuming a Web Service using Visual Studio .NET

This article will go through the complete process of how to create a Web Service and then how to consume it in any ASPX page. We'll do this entirely within the Visual Studio.NET. Our Web Service will convert Fahrenheit degrees to Celcius.

Published: Nov 18, 2002
Tested with: ASP.NET 1.1, Visual Studio 2002
Category: ASP.NET
43,561 views

Introduction

This article will go through the complete process of how to create a Web Service and then how to consume it in any ASPX page. We'll do this entirely within the Visual Studio.NET. Our Web Service will convert Fahrenheit degrees to Celcius.

What is a Web Service?

The buzz word around IT these days is Web Services. It has actually taken many years for Web Services to evolve to what they are today. A Web Service is defined as "a component of programmable application logic that can be accessed using standard web protocols". It's basically a component, or an assembly in ASP.NET, that can be accessed over the web. Anyone with a browser can see and use this application logic.

Generically speaking, a Web Service has inputs and outputs: it accepts some kind of request from the client and returns some results. This is what a public search engine like Yahoo! does. Everyone is talking about XML Web Services and the term is being used synonymously with Web Services. However, a distinction has to be made here for clarity, because they are 2 different things. A search engine like Yahoo! is an HTML Web Service. This specific kind of service requires a user to actively interact with the service and interpret the results. On the other hand, an XML Web Service returns the results in an XML format and it is self-describing. It is therefore smart enough to be able to communicate between servers and perform actions based on the returned results.

The returned results are wrapped in a specification which is called Simple Object Access Protocol (SOAP). This is a W3C specification, and it is a format which describes the data that is sent over HTTP. It is flexible enough (and complicated) to allow for a Web Service to be self-describing. This is a complex matter, which I will not be covering in this article. More information on these protocols can be found at the World Wide Web Consortium site (W3C).

Starting a new Project in Visual Studio.NET

To create a new project go to File > New > Project.

New Visual Studio Project

We will see the above dialog box come up. On the left, under Project types, we choose the language we want to build our solution in (Visual Basic in this case). On the right, under Templates, choose ASP.NET Web Service. At the bottom, in Location, we choose the location and the name of our project. Notice that I saved mine under the localhost, meaning that it adds this new project to the website already in place on my server.

When we click on OK, Visual Studio (VS) does 2 things:

New Application under the website

First, it creates a new virtual application in our website, under the location that we specified. In the screen capture above of the IIS, we can see that a new virtual folder was added to the location that we specified. Remember this was http://localhost/articles/nov182002/DegreesWebService.

Solution Explorer in VS.NET

The second thing that VS does, is create some sample files in the application. The Solution Explorer window inside VS above, shows all the files that were created. We can go ahead and erase the files Service1.asmx and Global.asax.

Adding a new Web Service to our Project

First thing to do is add a Web Service form to our project. We can do that by going to Project > Add Web Service.

Add New Web Service dialog box

The Web Service from the Templates should already be chosen for us. We need to type a Name in the textbox, making sure we give it the extension ASMX. When we click on Open, VS actually creates 2 files by default: the default.asmx, and the codebehind file default.asmx.vb. Let's take a look at each of the files created by VS.

1 <%@ WebService Language="vb" Codebehind="default.asmx.vb" Class="DegreesWebService._default" %>

The default.asmx file has only one line of code as shown above. It simply declares this page as a Web Service, and tells it to look in the codebehind page for the class degrees._default so that it inherits from it. The Codebehind parameter is used by Visual Studio and is not necessary to make this code work. Actually, at runtime, this page will simply ignore the Codebehind parameter and use the Class parameter instead.

Original source of code of an .asmx file

This file is not very much different from a regular web form (aspx page). A new class is created and any code should go inside this class. There are however, 4 characteristics that make this page a Web Service:

  1. The "Imports System.Web.Services" brings in the functionality needed under this class.
  2. The "<WebService(Namespace := "http://tempuri.org/")> _" makes this class callable from the web.
  3. The class contains the line "Inherits System.Web.Services.WebService", which makes this class inherit all the methods and properties of this class.
  4. The "<WebMethod()>" in front of a method makes this callable from the web. If it's not there in one of the functions, we will not be able to use it in our Web Service, even if the whole class is made available through the <WebService> statement (as in no. 2).

Creating a custom method inside the Web Service

At this point, let's create our custom method, that will change Fahrenheit degrees into Celcius. Since this method is going to output a single numeric value, let's make it a function instead. Let's first look at the final source code - default.asmx.vb.

1 Option Explicit On
2 Option Strict On
3
4 Imports System.Web.Services
5
6 <WebService(Namespace:="http://www.xefteri.com/articles/nov182002/DegreesWebService/")> _
7 Public Class Converter
8     Inherits System.Web.Services.WebService
9
10     <WebMethod()> _
11     Function FahrenheitToCelcius(ByVal strFahrenheit As String) As String
12         'define the variables
13         Dim strOutput As String = ""
14         Dim decCelcius As Decimal
15         'convert to Celcius
16         decCelcius = (((Convert.ToDecimal(strFahrenheit) - 32) / 9) * 5)
17         'round to 2 decimal places
18         decCelcius = Math.Round(decCelcius, 2)
19         'convert it back to a string
20         strOutput = Convert.ToString(decCelcius)
21         'return output of the function
22     Return strOutput
23     End Function
24
25 End Class

What did we do here? The Option Explicit and Option Strict have been turned on to make Debugging and Error Handling better with Visual Basic. Then we got rid of the default Namespace (http://tempuri.org/) inside the WebService brackets, and replaced it with our own. We can type anything we want here really, and it will work fine.

Notice that everything inside the class was deleted, and replaced with our custom FahrenheitToCelcius function. The function itself is a very simple one. It accepts a single parameter, strFahrenheit, in the form of a String, converts it first to a Decimal so we can work with it, changes it to Celcius with our formula, rounds it to 2 decimal places, changes it back to a String, and finally returns it. The function is preceded by the <WebMethod> statement once again, which makes this function callable from the web.

Building and testing the Web Service

Let's build and test our Web Service. We have to make sure that our starting page for the project is the default.asmx page: we right-click on the filename in the VS Solution Explorer, and select "Set As Start Page" from the pull down menu. Then go to Debug > Start, or press F5. VS builds the project and pops up a web browser window with this file. It should be noted here that a Web Service is not usually used to serve a web browser directly. This is simply a medium that Microsoft has provided so that we can test our Web Service.

Web Service testing

The nice thing about using VS is that it does a lot of the work behind the scenes. From the screen capture above, we see that first of all we have a listing of the operations that have been web-enabled. As we have seen earlier, these are the ones that have the <WebMethod> in front of them. We also have a link to the Service Description. This is the Web Service Description Language (WSDL), which is the XML grammar for describing Web Services. This is a Microsoft co-submitted W3C specification. This description includes everything we need to know about our Web Service, such as where to find it, what properties and methods are supported, the data types, and the protocols used to communicate with it. We can use this WSDL file to build proxies that clients can use to communicate with our Web Service. We'll see how to do that later on.

Enter values for WebService

Clicking on the link provided for our function, takes us to another screen, where .NET provides a nice interface for us to test our Web Service through the HTTP GET protocol. We enter a value in the textbox provided (100 in this case), and press the Invoke button.

Result of WebService

This opens up another window, where the result is returned to us in an XML file. In this case, 37.78 is the equivalent of 100 Fahrenheit in Celcius. It is returned as a string, rounded to 2 decimal places, just like our function should behave. This XML file is a simple one, having only one node, which has an attribute xmlns set equal to the value of our <WebService> Namespace. Since we are using the HTTP GET protocol to test this service, we can change the URL directly, replacing the value of strFahrenheit from 100 to something else and we will get our new response.

So now our Web Service is ready. Anyone with a browser can access it and use it.

Adding the Web Service as a Reference to a Project

To use, or consume, our Web Service, we must first make a Web reference to the WSDL file that was created by VS. Go to Project > Add Web Reference.

Add Web Reference dialog box

In the dialog box that comes up, type in the complete URL of the Service Description of the Web Service, or the WSDL file. In our case, this file's URL is http://www.xefteri.com/articles/nov182002/DegreesWebService/default.asmx?WSDL. VS will fetch the WSDL file, and if everything is fine, it will display it on the left, and enable the Add Reference button at the bottom, so we can add it to our Project. Click on the button to do so.

Solution Explorer window after adding a Web Reference

The refreshed Solution Explorer now shows the addition of the Web Service as a Web Reference. It's given the name com.xefteri.com, and that is going to be our Namespace as we call its methods and properties, as we will see later on. We can simply rename this to whatever we want, and it will propagate to the examples below.

By adding the Web Reference, VS has connected to the Web Service, parsed the WSDL, and generated a proxy class which we can use to program with. A proxy is some code that does work on behalf of other code. The proxy looks and feels the same as the Web Service we are calling. It has the same methods and properties, but it it does not contain the actual implementation. It simply acts as a go-between our code and the Web Service, so that we don't have to deal with the complicated details of the Web Service in XML.

Consuming the Web Service

When we use this Web Service, or any other, we typically do so within an ASPX web form. So, let's see how to use, or consume, this Web Service we just created inside an ASPX page. We could start a new ASP.NET Web Application Project to do this, but for simplicity's sake we'll just add a web form to our existing Project. Go to Project > Add Web Form and name our file default.aspx. When we create our new form, VS actually creates 2 files: the first one is the default.aspx and the second is the codebehind, default.aspx.vb.

We'll modify the default.aspx page to add a textbox, a button and a label. We'll name them txtInput, btnConvert and lblCelcius respectively.

1 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="default.aspx.vb" Inherits="DegreesWebService._default"%>
2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
3 <HTML>
4 <HEAD>
5     <title>default</title>
6     <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
7     <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
8     <meta name="vs_defaultClientScript" content="JavaScript">
9     <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
10 </HEAD>
11 <body>
12 <form id="Form1" method="post" runat="server">
13     Enter your value in Fahrenheit:
14     <asp:TextBox id="txtInput" runat="server"></asp:TextBox><br>
15     <b>
16     <asp:Button id="btnConvert" runat="server" Text="Convert to Celcius"></asp:Button><br>
17     <br>
18     <asp:Label id="lblCelcius" runat="server" Visible="False"></asp:Label>
19 </form>
20 </body>
21 </HTML>

VS takes care of the first line of code in this file. It knows to look in the codebehind file, and when deployed to inherit from the _default class of the codebehind. Since our whole Namespace is DegreesWebService, then this class becomes DegreesWebService._default.

1 Option Explicit On
2 Option Strict On
3
4 Public Class _default
5     Inherits System.Web.UI.Page
6
7     Protected WithEvents txtInput As System.Web.UI.WebControls.TextBox
8     Protected WithEvents btnConvert As System.Web.UI.WebControls.Button
9     Protected WithEvents lblCelcius As System.Web.UI.WebControls.Label
10
11     Dim myWebService As New com.xefteri.www.Converter()
12
13     Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
14         lblCelcius.Text = "Celcius = " + myWebService.FahrenheitToCelcius(txtInput.Text)
15         lblCelcius.Visible = True
16     End Sub
17
18 End Class

Let's take a closer look at what we have done here. The codebehind is wrapped inside a class called _default, which inherits from the System.Web.UI.Page. We also have our three web controls that we use in the default.aspx page defined here so we can use them. Most important of all is the variable myWebService, which is a new class of com.xefteri.www.Converter(). This is a class that resides in our system after the addition of the Web Service as a Web Reference. It is actually an instance of our proxy class. By declaring our variable as a class of this type, we now have access to the Web Service's methods and properties.

Our only existing Sub handles the button click, and we simply set the text of the label control equal to what is returned from our FahrenheitToCelcius function we created earlier. We make sure we pass into that function the value of the input box, and finally we set the label control visible, since it was set to invisible initially.

Conclusion

In this article, we have gone through how to create and consume a Web Service using Visual Studio.NET. Using Studio, this is extremely easy to do, but not necessary. We could have used instead the world's most popular editor - Notepad, and compile our DLL with the command prompt. The .NET framework is needed though to run our creation.

 



Other articles in this category
  1. Smart headers and footers using ASP.NET User Controls
    December 23, 2002
    Good site usability often means removing links from one page back to itself. In this article we will look at how to create an ASP.NET User Control which will act as a common header to a site. It will automatically know which page we are looking at, and it will remove links to the same page from itself. For example, on this site, if we click on the About us section of the header, it will take you to the page, and it will make that link inactive. That way, we know that we are under that section, and we can't click on it anymore.
  2. Maintaining Sorting while Paging in an ASP.NET Datagrid
    December 18, 2002
    The Datagrid server control offers much control and flexibility in presenting data. Two of the actions that are hard-wired into it are Paging and Sorting. On their own they work great, but not so well together. When you sort a column and then move to a previous or next page, the sorting preference is not maintained. In this article we will see how to maintain both by using the Viewstate object.
  3. How postback works in ASP.NET
    December 10, 2002
    In this article, we will take a closer look at how ASP.NET pages post back to themselves, and how to customize this feature in our web applications.
  4. Viewing and editing file and directory attributes in ASP.NET
    December 2, 2002
    The System.IO.FileAttributes class gives us access to file/directory attributes. In this article, we'll see how to use this class to first read the current attributes and then change them.
  5. Copying a directory in ASP.NET
    November 25, 2002
    The System.IO.DirectoryInfo class does not come with a method to copy a directory. In this article, we'll see how to create a method to do that, and then use it in an ASP.NET page.