深蓝海域KMPRO

Building an ASP.NET Web Service

2002-09-12 11:34

Building an ASP.NET Web Service

Srinivasa Sivakumar

Web services allow you to call a function that exists on another machine on the Internet, using standard protocols. Srinivasa Sivakumar explains how to create Web services using the Microsoft .NET Framework and how to access the Web service via HTTP-Get, HTTP-Post, and SOAP protocols.

Web services provide the ability for a server on the Internet to provide an interface to functionality there. Therefore, you can create an API that can be called from anywhere on the Web. There are sites that provide this kind of capability, but usually the technologies they use to implement them are proprietary. There are standards under development to make creating Web services easier—most notably, the Simple Object Access Protocol (SOAP).

The new Microsoft .NET Framework has embraced SOAP and other standardized technologies and has provided an interface for creating Web services that's easy to use. In this article, I'll explain how to use ASP.NET to build your own Web service.

Architecture of Web services

Before getting in too deep, I want to show you the architecture of a Web service. Figure 1 is a bird's eye view of a typical Web service architecture. Site X is offers Web services, and sites A, B, and C access them via the Internet.

Web services provide a very generic way for applications to work together. In fact, there are bound to be many, many Web services made available over the next few years. For example, a financial services vendor might provide Web services that would allow you to retrieve the current value of a stock, buy and sell stocks, retrieve stock performance data for a given period, maintain a customer stock portfolio, and so forth. Then, if you want to create a site that provides a stock look-up, you can accomplish it by subscribing to the financial services vendor's Web service. You don't have to write the code or maintain the data. You just provide the page for the user to enter his or her information and call the Web service behind the scenes.

This provides new site owners with a wealth of capabilities to add to their Web site: stock trading, online world news coverage, and so on—all just by subscribing to the Web services.

And the good news is that the technical side of implementing Web services is simple. Now you can build a customer portal in weeks by subscribing to the Web services.

Now that you have good understanding of Web services, I'll show you how to build one with the .NET Framework.

Using the Visual Basic .NET language

The .NET Framework allows you to create ASP.NET pages, Web services, and even complete applications with a built-in compiler. You can create applications in C# (pronounced "C-sharp"), Microsoft's newest language, or in a language called Visual Basic .NET. Visual Basic .NET is the newest version of the language that powers the Visual Basic development environment, but its use has been extended. In addition to writing Windows applications in the Visual Basic development environment, you can now build ASP.NET pages and Web services using the Visual Basic language without the development environment. All you need is the .NET Framework.

Building a Web Service

Building a Web service is as easy as writing a Visual Basic class. In Visual Basic 6, you had public, private, and friend methods. VB.NET allows you to specify that a method is a WebMethod. This enables access to this method from anywhere on the Internet.

I'm going to build a Web service that has two functions: One converts kilograms into pounds; the other, vice versa. Fire up Notepad (or your favorite text editor) and type in the following code. Then save the file as Conversion.asmx. (The .ASMX extension is used by .NET Framework to indicate an ASP.NET page. You can also use this extension when creating a Web service.)

<%@ WebService Language="VB" Class="Conversion" %>  'To create Web Methods, we need to import 'the namespace System.Web.Services Imports System.Web.Services  'Create the Conversion class Class Conversion    'Create the KilogramsToPounds Web Method    Public Function <WebMethod()>KilogramsToPounds _       (ValueInKilograms As Double) As String       KilogramsToPounds = cstr(ValueInKilograms * 2.2)    End Function     'Create the PoundsToKilograms Web Method    public Function <WebMethod()>PoundsToKilograms _       (ValueInPounds As Double) As String          PoundsToKilograms = cstr(ValueInPounds/2.2)     End Function End Class

On the first line, I indicate that this file contains a Web service, specify the language used by the Web service (VB), and then specify the class name (Conversion). In the next line, I import the System.Web.Services namespace into the application. This is similar to setting reference to an object via the "References…" dialog box in VB 6. Then I create a class with two public methods. You can see the new syntax used to identify Web methods: <WebMethod()>.

Now start IIS5, create a virtual directory called "WebServices," and copy the Conversion.asmx into the directory.

Now it's time to test the Web service. Fire up Internet Explorer and connect to the Web services virtual directory (http://localhost/Webservices/Conversion.asmx). When you access the .ASMX file, the .NET Framework creates an HTML page including the information about the services offered by the .ASMX file that you're accessing. Figure 2 shows the Web service information.

This HTML page also includes the code to access the Web services via the HTTP-Get method. Figure 3 shows how to access the KilogramsToPounds and Figure 4 shows how to access the PoundsToKilograms Web services via the HTTP-Get method. (You'll see a reference to something called an SDL Contract at the bottom of Figure 2. Don't worry about that right now. I'll cover SDL a little later in this article.)

Accessing a Web service with HTTP-Get and HTTP-Post

You've built your Web service. Now, you'll find out how to access the Web service via HTTP-Get and HTTP-Post. Create an HTML page with two forms, each including one text box and one button, as shown in Figure 5.

Then, in the first form, set the attribute METHOD to Get and ACTION to http://localhost/WebServices/Conversion.asmx/KilogramsToPounds. Then name the first textbox ValueInKilograms. Here's what the form should look like:

<FORM Method="Get"  action=http://localhost/WebServices/Conversion.asmx/ KilogramsToPounds> <TD>Enter the Value in Kilograms:<BR> <INPUT size=50 name=ValueInKilograms>  <INPUT type=submit value="Get Pounds"> </TD> </FORM>  

This form will access the KilogramsToPounds Web method defined in the Conversion.ASMX file, and the value entered in the ValueInKilograms text box will be passed as the parameter to the Web method.

In the same way, change the second form's ACTION attribute as http://localhost/WebServices/Conversion.asmx/PoundsToKilograms and its textbox name to ValueInPounds.

Notice that you're directly accessing the KilogramsToPounds and PoundsToKilograms Web methods in the HTML Form's action attribute. You'll also notice that you've named the textboxes as the name of the parameters of the Web methods.

Save the HTML file and load it in the browser. Enter the number 2 in the first text box and click the Get Pounds button. You should see the results shown in Figure 6.

Notice that you got the result in XML format. That's what you'll get when you access a Web service. In the same way, you can also access the Web services via the HTTP-Post method by changing the HTML form's action attribute to Post.

What is SOAP?

The major players in today's distributed computing architecture are COM and CORBA/EJB. And of course, it's difficult to communicate between systems written in these two approaches. Some software bridges exist, but they're typically inefficient. Another problem is that if the communication between the systems requires going through a firewall, then the firewall has to be reconfigured to accommodate the traffic. Doing this, however, can lead to security holes.

To address these problems, Microsoft, IBM, and others jointly submitted a proposal for a common, lightweight protocol called SOAP (Simple Object Access Protocol). SOAP is based on a simple XML-RPC protocol developed by Dave Winer of UserLand. Its implementation is very simple. It describes how procedures can be called and how results can be returned from procedures using XML sent over HTTP. Since SOAP is based on existing, simple technologies, it's highly efficient and easy to create and work with. In addition, since it uses the HTTP protocol, which is typically open in firewalls, it helps avoid some of the security holes introduced by other methods.

So how does SOAP apply to Web services? Well, since Web services are nothing more than procedures made available to be called over the Internet, it makes sense that SOAP would be a good way to make those calls and receive the results.

SOAP and SDL

But when you access Web services via SOAP, you need to know exactly what services are offered by a site and what arguments they expect. This information can be obtained through an SDL (Service Description Language) file. The .NET Framework helps you build the SDL file very easily. To create the SDL file for a Web service, just call the Web service URL with the SDL in the query string, like this:

http://localhost/WebServices/Conversion.asmx?SDL

Figure 7 shows the generated SDL document.

To access Web services (such as KilogramsToPounds) via SOAP, you must know how to marshal and serialize the SOAP request and response. To do this, you need to build a proxy to manage the marshalling and serializing. This involves two steps. First, you'll build a proxy for your Web service with the help of the WebServiceUtil.Exe file. Then you'll take the code generated by the WebServiceUtil.Exe file and compile it into a COM DLL.

Building the proxy

First, I'll show you how to build the proxy. (I've included a Proxy.Bat file, which does it for you, with my Download file for this article. You can copy all of the code into the IIS virutal directory and run the BAT file from there.)

Webserviceutil /C:proxy    /pa:http://localhost/WebServices/Conversion.asmx?sdl   /l:VB /n:NameSpaceKgToILB

The first parameter (/C) asks the WebServiceUtil.Exe to build a proxy file. The second parameter (/pa) asks it to use the SDL generated by the given URL. The third parameter (/l) asks it to generate VB code. The last parameter (/n) provides a namespace for the Web service.

The Proxy.Bat file generates Conversion.vb. When you look at Conversion.vb, you'll see the functions KilogramsToPounds and PoundsToKilograms. In addition, you'll also notice Begin and End functions for both the KilogramsToPounds and PoundsToKilograms functions. These functions are used to call the Web services asynchronously.

Now you can use the generated VB code and build the DLL file. (I've also included the DLL.Bat file, which does it for you, in the Download file.) Call the VB.NET command line compiler to compile the Conversion.vb file into a DLL file.

vbc /out:KGTOIBL.dll /t:library    /r:System.Xml.Serialization.dll    /r:System.Web.Services.dll Conversion.vb

The first parameter (/out:) specifies the DLL file that you're going to generate. The second parameter (/t:) specifies that you're going to generate a library. The third and fourth parameters (/r:) specify the libraries to be included when compiling the DLL file. The last parameter is the source filename, Conversion.vb.

If you look at the Conversion.vb file, you'll see that you're importing the System.Xml.Serialization, System.Web.Services.Protocols, and System.Web.Services namespaces. The first namespace resides in the System.Xml.Serialization.DLL file. The next two namespaces reside in the System.Web.Services.DLL file. That's why you're including these two DLL files with the /r: compiler switch.

Deploying the proxy

The result of this process is the KGTOIBL.DLL file. So now you need to deploy the new DLL. Create a directory named BIN under the WebServices virtual directory and copy the KGTOIBL.DLL file.

That's it! You're done with DLL file deployment. No, I'm not joking. With the .NET Framework, you don't need to register the DLL with RegSvr32.

How does the .NET framework know to create the object when a service asks for the namespace? Microsoft assumes that every Web application has a BIN folder. Under BIN, all of the custom objects, like this DLL file, are stored. Therefore, when you create a custom object for the Web application, .NET runtime searches for the object in the BIN directory and creates the object for you. If it doesn't find the object in the BIN directory, then you get an error.

Consuming a Web service with SOAP from ASP.NET

Next you'll build an ASP.NET page: SoapWebService.ASPX in the IIS Virtual Directory. It will access the Web service via the SOAP protocol. This ASP.NET page will hold two labels:

<form runat="server">  <P><FONT face="Verdana, Arial" size=5><B>Using Web  Service Via SOAP</B></FONT><HR></P>  Web Method KilogramsToPounds: <asp:Label id="lblKGs"  runat="server" /><BR><BR> Web Method PoundsToKilograms: <asp:Label id="lblLBS"  runat="server" /> </form>    Let's add some code in the Page_Load event.   <script language="vb" runat="server"> Sub Page_Load(Sender As Object, E As EventArgs)  Dim objConv as new NameSpaceKgToILB.Conversion   lblKGS.Text = objConv.KilogramsToPounds(1) lblLBS.Text = objConv.PoundsToKilograms(5)  End Sub </script>
This code instantiates an object of NameSpaceKgToILB.Conversion, as you might do in VB6. It then calls the two Web methods and assigns the return values to the labels.

Now copy the ASP.NET file in to the Web Services virtual directory and call the ASP.NET page from a browser. Figure 8 shows the result.

Summary

You've built a Web service, and you've accessed the Web services via HTTP-Get, HTTP-Post, and finally the SOAP protocol. You don't need to have a deep understanding of XML and SOAP to build these services. The Microsoft developers clearly put a lot of effort into making the .NET platform easy to use.

Until next time, happy programming!

Download SIVAKUMA.ZIP

Sidebar: Getting it All up and Running

To create and use the example in this article, you'll need Windows 2000 with Internet Information Server (IIS) 5 and Internet Explorer 5.5. In addition, you'll need the Microsoft .NET Framework SDK Beta 1.

You can only run Beta 1 of the Framework on Windows 2000. However, you shouldn't install this beta product on any production machines. There's no guarantee that it won't cause other software to break or screw up your configuration in one way or another. Microsoft has, of course, worked to make sure that doesn't happen, but you should always be careful with beta software.

Internet Explorer 5.5 may be included with Windows 2000. If you need to download it, you can get it from the Microsoft Web site at http://www.microsoft.com/windows/ie/.

The .NET Framework can be downloaded from the Microsoft site, too. Go to http://msdn.microsoft.com/net/.

Once you arrive at that page, click on .NET Downloads in the list along the left side of the page. Be aware that this download is very large—111M. If you prefer, you can order it on CD-ROM for a minimal shipping-and-handling fee. You can do that at http://developerstore.com/devstore/product.asp?productID=7597.

Sidebar: Further Reading

MSDN Download: .NET Framework SDK Technology Preview

http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdn-files/027/000/976/msdncompositedoc.xml

MSDN Show: .NET Architecture Overview

http://msdn.microsoft.com/theshow/

Article: Simple Object Access Protocol (SOAP) Specification, Version 1.1

http://msdn.microsoft.com/xml/general/soapspec.asp

Article: Discovery of Web Services (DISCO)

http://msdn.microsoft.com/xml/general/disco.asp

相关推荐