您可以在这里快速查找:


 
您的位置: 编程学习 > asp.net教程 > 200507
文章分类

Java技术
2005: 03 04 05 06 07 08
09 10 11 12
2006: 01 02

Asp.net
2005: 07 08 09 10 11 12
2006: 01 02

VB编程
2006: 02

Asp编程
2005: 11 12
2006: 01 02

C++/VC
2005: 10 11 12
2006: 01 02

Delphi
2005: 12
2006: 01 02

其它

 本文章适合所有读者

Web Services: Building Reusable Web Components with SOAP and ASP.NET(English)

x86

 

Web Services: Building Reusable Web Components with SOAP and ASP.NET

David S. Platt
This article assumes you’re familiar with XML and Visual Basic
Level of Difficulty     1   2   3 
Download the code for this article: WebComp.exe(93KB)
Browse the code for this article at Code Center: TimeServiceDemo
SUMMARY XML and HTTP are cross-platform technologies especially suited for building applications that can communicate with each other over the Internet, regardless of the platform they are running on. Web Services in the Microsoft .NET Framework make it easy to write components that communicate using HTTP GET, HTTP POST, and SOAP.
An understanding of these concepts, along with knowledge of synchronous and asynchronous operations, security, state management, and the management of proxies by the .NET Framework is essential in building these applications.
This article has been adapted from David Platt’s upcoming book introducing the Microsoft .NET Platform to be published by Microsoft Press in Spring 2000.
seismic shift is just now beginning in Internet programming. Internet access will soon be built into nearly every program anyone ever writes. You won´t use a generic browser, except when you feel like browsing generically. Instead, you will use dedicated programs that are optimized for accomplishing specific tasks. You won´t be aware of the program´s Internet access (except when it breaks).
An early example of this type of program is Napster, which allows you to search the shared hard drives of thousands of participating users for music files that meet specified criteria, and download the ones you like. The dedicated user interface of a multi-player game is another example of hidden Internet access. And the latest edition of Microsoft® Money does a good job of seamlessly blending Web content (current stock quotes, latest balances, and so on) and desktop content (financial plans you create locally).
In order to develop programs of this type, there needs to be a quick and easy way (which, in turn, means a cheap way) to write code that communicates with other programs over the Internet. The idea isn´t new; there are a number of existing technologies that enable this type of communication: RPC, DCOM, and Microsoft Message Queue Services (MSMQ). Each of these techniques is cool in itself, but they all share one fatal failing: they only work from one similar system to another. MSMQ talks only to MSMQ, a DCOM client only to a DCOM server, and so on.
What´s really needed is universal programmatic access to the Internet—some way for a program on one box to talk to any other program on any other box. It has to be independent not only of the operating system, but also of the programs´ internal implementations. (Is it C++ or Visual Basic®? Which vendor is it from? Which version is it? Right now you can barely solve this problem on a single desktop.) And it has to be easy to program, or no one will be able to afford it.

Solution Architecture
The only way to deal with the enormous numbers of heterogeneous entities on the Internet is to use the lowest common denominator. In other words, when bytes are transferred from one box to another, the process needs to use some standard that everyone on the Internet supports. The most common Internet transfer protocol is HTTP, which is used today by essentially all Web browsers to request the pages they display. The emerging cross-platform standard for encoding pure information transferred over HTTP is XML.
Microsoft put these ideas together and developed the concept of a Web Service—a seamless way for objects on a server to accept incoming requests from clients using HTTP and XML. To create a Web Service, you simply write a Microsoft .NET server object as if it were going to be accessed directly by local clients, mark it with an attribute that says that you want it to be available to Web clients, and let ASP.NET do the rest. It automatically hooks up a prefabricated infrastructure that accepts incoming requests through HTTP and maps them to calls on your object, as shown in Figure 1. By rolling them into a Web Service, your objects can work with anyone on the Web who speaks HTTP and XML, which should be everybody. You do not have to write the infrastructure that deals with Web communication—the operating system provides it for you.


Figure 1 Handling HTTP Requests

On the client side, .NET provides proxy classes that have easy, function-based access to the Web Services provided by any server that accepts HTTP requests, as shown in Figure 2. A developer tool reads the description of the Web Service and generates a proxy class containing functions in whatever language you´re using to develop the client. When your client calls one of these functions, the proxy class generates an HTTP request and sends it to the server. When the response comes back from the server, the proxy class parses the results and returns them from the function. This allows your function-based client to seamlessly interact with any Web server that speaks HTTP and XML.


Figure 2 Proxy Classes

Writing a Web Service
As I always do when explaining a new piece of technology, I wrote the simplest program I could to demonstrate Web Services. This sample Web Service provides the current time of day on its machine in the form of a string, either with or without the seconds digits. You can download the sample code for this service from the link at the top of this article to follow this description more closely. You will need to download and install the Microsoft .NET SDK if you want to run it as well.
I wrote this Web Service in the form of an .asmx page to avoid distracting you with other software packages. I first installed the .NET SDK. Then I used the administrative tools in Microsoft Internet Information Services (IIS) to set up a virtual directory pointing to the folder in which I would do my service file development. Then I wrote my ASP.NET code in a file called TimeService.asmx on my server.
Writing the Web Service was incredibly easy; I did it in Notepad (see Figure 3). While it´s quite simple, there are a few constructs that are probably new to you, so let´s go over it section by section. (You should note that the code in this article is based on pre-Beta 1 bits and the calls may change somewhat before the final release.) The program starts with the standard ASP.NET salutation <%@...%>. In it, the WebService directive tells ASP.NET that the code on the page is to be exposed as a Web Service. The Language attribute tells ASP which language to compile the page´s code in accordance with. I´ve chosen Visual Basic because it´s familiar to the majority of developers. ASP.NET will use Visual Basic.NET to compile the code. You do not have to install Visual Studio®; all the language compilers come with the .NET SDK. The Class attribute tells ASP.NET the name of the class of object to activate for incoming requests addressed to this service.
The rest of the page contains the code that implements the class. I first use the Imports directive, a new feature of Visual Basic.NET, which tells the compiler to import the namespaces. The term "namespace" is a fancy way to refer to the description of a set of prefabricated functionality. It is conceptually identical to a reference in your Visual Basic 6.0 project. Since ASP.NET will compile this example´s code "just-in-time" when a request arrives from a client, I don´t have a project in which to set these references, so I have to explicitly add them to the code. The names following Imports tell the compiler which sets of functionality to include the references for. In this case, System and System.Web.Services contain the prefabricated features you need to write a Web Service.
The next line defines the name of the class. This class in Visual Basic is similar to many you´ve written. You´ll see a brand new keyword (Inherits) at the end of the line: Inherits WebService. This represents one of the main enhancements in Visual Basic.NET—support for the object-oriented concept called inheritance. When you say that your new TimeService class inherits from the WebService class, you are telling the compiler to take all the code from the system-provided class named WebService (known as the base class) and include it in your new TimeService class (known as the derived class). And in addition to reusing the code from the class you inherit from, you can add, alter, and override the functionalities of that class in your new clan. Think of inheritance as cutting and pasting without actually moving anything. In fact, seriously deranged C++ and Java-language geeks often refer to physically cutting and pasting code as editor inheritance.
The WebService class is provided by the new .NET runtime library, just as many objects used in Visual Basic 6.0 were provided with the operating system. WebService contains all the prefabricated plumbing required to handle the incoming HTTP requests and route them to the proper methods on your object.
I´m often asked what the difference is between importing the namespace and declaring inheritance. In other words, what´s the difference between the Imports and Inherits keywords? Well, the Imports statements only bring in the description of a set of functionality, it doesn´t actually make use of it. As I said before, it´s like setting a reference. The Inherits keyword actually takes part of the code referred to in the description and uses it. It´s like Dim on steroids.
Now that I´ve defined my class, I need to define the methods and functions of the class. Again, this is very similar to the way it worked in Visual Basic 6.0, but with one new twist: you have to add a new attribute, <WebMethod()>, to every method that you want exposed to Web clients. This tells ASP.NET that the method in which it appears is to be exposed to clients as a Web Service. You´ve seen plenty of attributes in Visual Basic 6.0, such as public, private, and const. The .NET Framework and Visual Basic.NET use many more of them, which is why there´s a new syntax for specifying them. Just as your class can contain public and private methods, so can it contain some methods that are exposed to Web clients and others that are not.
Finally, let´s get down to the internals of the class´s method. The handling of the date and time variables in my code may look a little strange to you; it was to me. Don´t worry about it, it´s just how Visual Basic.NET deals with dates and times.


Figure 4 TimeService.asmx in a Browser

Now let´s access the Web Service from a client. ASP.NET contains good prefabricated support for this as well. If you fire up Microsoft Internet Explorer 5.5 and request the ASP.NET page I just wrote, you will see the page shown in Figure 4. ASP.NET detects the access to the Web Service page itself (as opposed to one of the methods within the service), and responds with a page of information about the service. This shows you all the methods that ASP.NET found in the target class (in this case, only GetTime), and provides a test capability for each method. Enter True or False to tell it whether to show the seconds digits or not, click Invoke, and the test page will call the specified method and return the results (if you entered TRUE), as shown in Figure 5. Note that the parameters are passed in the URL, and the results are returned as XML via the GET protocol. Also note that you must open the page in a way that goes through IIS, typing in a qualified UTL such as http://localhost/your virtual directory name/timeservice.asmx. If you simply double-click the page in the Explorer view of your hard disk, you´ll bypass IIS and ASP.NET and simply receive the text of the .asmx page, which isn´t what you´re looking for.


Figure 5 Show Seconds

That´s all I had to do to write my Web Service. It only took 13 lines, counting else and endif. How much easier does it get?

Self-description of Web Services: The SDL File
In order to allow programmers to develop client apps that use my Web Service, I need to provide the information that they need to have during their design and programming process. For example, a client of my Web Service would probably like to know the methods the Web Service exposes, the parameters required, and the protocols supported—something conceptually similar to the type library that a standard COM component would carry. The problem with type libraries, however, is that they are Microsoft COM-specific, and you may want non-Microsoft systems to be able to consume your Web Service as well. You may also want to be able to write descriptions of non-Microsoft services running on non-Microsoft systems, so that your Microsoft-built client applications can use these services. What you need is a universal method of describing a service. And you need it to be machine-readable, so that intelligent development environments can make use of it.
ASP.NET provides such a descriptive service. When it compiles a Web Service, ASP.NET can produce a file listing the protocols supported by the service and the methods provided and parameters required by that service. The file is encoded in XML and uses a vocabulary called Service Descriptor Language (SDL). The SDL file of a Web Service is sometimes known as its contract because it lists the things that the service is capable of doing and tells you how to ask for them.
You obtain the SDL file from ASP.NET by requesting the .asmx file with the characters ?SDL attached to the URL. For example, on my local machine, I obtained the SDL file for my sample Web Service by requesting the URL http://localhost/AspxTimeDemo/TimeService.asmx?SDL. Since I´m not exposing the sample service on an actual running server, I´ve provided this file in the sample code.
When you wrote COM components in Visual Basic 6.0 and Visual C++® 6.0, you sometimes wrote the component first and then wrote a type library to describe it. Other times you started with a type library describing an interface and wrote code that implemented it. SDL can work in both of these ways as well. You could write the code first, as I´ve done in this sample, in which case ASP.NET will generate an SDL file for interested clients. Alternatively, I could have written the SDL file first, describing what I´d like the service to do, and then use the utility program WebServiceUtil to generate a template file that implements the service that it describes (similar to the Implements keyword in Visual Basic 6.0).
The SDL file is somewhat complex, so I´ve extracted portions to discuss the principles (see Figure 6). The serviceDescription element is the root of the file. Everything inside it is part of the description of this Web Service. It contains an attribute giving the name of the Web Service, in this case, TimeService.