Published on ONDotNet.com (http://www.ondotnet.com/)
 See this if you're having trouble printing code examples

O'Reilly Book Excerpts: .NET Framework Essentials, 2nd Edition

Web Services

Related Reading

.NET Framework Essentials
By Thuan L. Thai, Hoang Lam

by Thuan L. Thai, Hoang Lam

Editor's Note: This is the first of four excerpts from the second edition of O'Reilly's .NET Framework Essentials, 2nd Ed. by Thuan L. Thai and Hoang Lam. The complete series of excerpts covers Web services in the context of the .NET framework. In this first part, they give a .NET Web services framework overview.

Web Services allow access to software components through standard web protocols such as HTTP and SMTP. Using the Internet and XML, we can now create software components that communicate with others, regardless of language, platform, or culture. Until now, software developers have progressed toward this goal by adopting proprietary componentized software methodologies, such as DCOM; however, because each vendor provides its own interface protocol, integration of different vendors' components is a nightmare. By substituting the Internet for proprietary transport formats and adopting standard protocols such as SOAP, Web Services help software developers create building blocks of software, which can be reused and integrated regardless of their location.

In this chapter, we describe the .NET Web Services architecture and provide examples of a Web Service provider and several Web Service consumers.

Web Services in Practice

You may have heard the phrase "software as services" and wondered about its meaning. The term service, in day-to-day usage, refers to what you get from a service provider. For example, you bring your dirty clothing to the cleaner to use its cleaning service. Software, on the other hand, is commonly known as an application, either off-the-shelf, or a custom application developed by a software firm. You typically buy the software (or in our case, build the software). It usually resides on some sort of media such as floppy diskette or CD and is sold in a shrink-wrapped package through retail outlets.

How can software be viewed as services? The example we are about to describe might seem far-fetched; however, it is possible with current technology. Imagine the following. As you grow more attached to the Internet, you might choose to replace your computer at home with something like an Internet Device, specially designed for use with the Internet. Let's call it an iDev. With this device, you can be on the Internet immediately. If you want to do word processing, you can point your iDev to a Microsoft Word service somewhere in Redmond and type away without the need to install word processing software. When you are done, the document can be saved at an iStore server where you can later retrieve it. Notice that for you to do this, the iStore server must host a software service to allow you to store documents. Microsoft would charge you a service fee based on the amount of time your word processor is running and which features you use (such as the grammar and spell checkers). The iStore service charges vary based on the size of your document and how long it is stored. Of course, all these charges won't come in the mail, but rather through an escrow service where the money can be piped from and to your bank account or credit card.

This type of service aims to avoid the need to upgrade your Microsoft Word application. If you get tired of Microsoft Word, you can choose to use a different software service from another company. Of course, the document that you store at the iStore server is already in a standard data format. Since iStore utilizes the iMaxSecure software service from a company called iNNSA (Internet Not National Security Agency), the security of your files is assured. And because you use the document storage service at iStore, you also benefit from having your document authenticated and decrypted upon viewing, as well as encrypted at storing time.

All of these things can be done today with Web Services.

In fact, Microsoft has launched a version of the "software as service" paradigm with its Passport authentication service. Basically, it is a centralized authentication service that you can incorporate into your web sites. At sites using the Passport authentication service, it's no longer necessary to memorize or track numerous username/password pairs.

Recently, Microsoft also announced .NET My Services (formerly codenamed "HailStorm"), a set of user-centric Web Services, including identification and authentication, email, instant messaging, automated alert, calendar, address book, and storage. As you can see, most of these are well-known services that are provided separately today. Identification and authentication is the goal of the Passport project. Email might map to Hotmail or any other web-based email services. Instant messaging and automated alert should be familiar to you if you use MSN Messenger Service or AOL Instant Messenger. A calendar and address book are usually bundled together with the web-based email service. Consolidating these user-centric services and exposing them as Web Services would allow the user to publish and manage his own information.

A .NET My Services customer can also control access permission to the data to allow or restrict access to content. These services also allow other users, organizations, and smart devices to communicate and retrieve information about us. For example, how many times have you been on the road with your mobile phone and wanted your contact list from Outlook? Your mobile phone should be able to communicate with your address book Web Service to get someone's phone number, right? Or better yet, if your car broke down in the middle of nowhere, you should be able to use your mobile phone to locate the nearest mechanic. The user is in control of what information is published and to whom the information will be displayed. You would probably have it set up so that only you can access your address book, while the yellow pages Web Service that publishes the nearest mechanic shop to your stranded location would be publicly accessible to all.

Currently, users store important data and personal information in many different places. With .NET My Services, information will be centrally managed. For example, your mechanic might notify you when it's time for your next major service. Or when you move and change your address, instead of looking up the list of contacts you wish to send the update to, .NET My Services will help you publish your update in one action.

The potential for consumer-oriented and business-to-business Web Services like .NET My Services is great, although there are serious and well-founded concerns about security and privacy. In one form or another, though, Web Services are here to stay, so let's dive in and see what's underneath.

Web Services Framework

Web Services combine the best of both distributed componentization and the World Wide Web, extending distributed computing to broader ranges of client applications. The best thing is that this is done by seamlessly marrying and enhancing existing technologies.

Web Services Architecture

Web Services are distributed software components accessible through standard web protocols. The first part of the definition is similar to COM/DCOM components. However, it is the second part that distinguishes Web Services from the crowd. Web Services enable software to interoperate with a much broader range of clients. While COM-aware clients can understand only COM components, Web Services can be consumed by any application that understands how to parse an XML-formatted stream transmitted through HTTP channels. XML is the key technology used in Web Services and is used in the following areas of the Microsoft .NET Web Services framework:

Web Service wire formats
The technology enabling universal understanding of how to perform data exchanges between the service provider and consumer; the format of data for the request and response.

Web Service description in WSDL (Web Services Description Language)
The language describing how the service can be used. Think of this as the instructions on the washing machine at the laundromat telling you where to put quarters, what buttons to push, etc.

Web Service discovery
The process of advertising or publishing a piece of software as a service and allowing for the discovery of this service.

Figure 6-1 depicts the architecture of web applications using Windows DNA, while Figure 6-2 shows .NET-enabled web applications architecture. As you can see, communication between components of a web application does not have to be within an intranet. Furthermore, intercomponent communication can also use HTTP/XML.

Figure 6-1. Windows Distributed interNet Architecture


Figure 6-2. NET-enabled web application framework


Web Services Wire Formats

You may have heard the phrase "DCOM is COM over the wire." Web Services are similar to DCOM except that the wire is no longer a proprietary communication protocol. With Web Services, the wire formats rely on more open Internet protocols such as HTTP or SMTP.

A Web Service is more or less a component running on the web server, exposed to the world through standard Internet protocols. Microsoft .NET Web Services currently supports three protocols: HTTP GET, HTTP POST, and SOAP (Simple Object Access Protocol), explained in the next sections. Because these protocols are standard protocols for the Web, it is very easy for the client applications to use the services provided by the server.


As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying protocol. The GET and POST methods of the HTTP protocol have been widely used in ASP (Active Server Pages), CGI, and other server-side architectures for many years now. Both of these methods encode request parameters as name/value pairs in the HTTP request. The GET method creates a query string and appends it to the script's URL on the server that handles the request. For the POST method, the name/value pairs are passed in the body of the HTTP request message.


Similar to HTTP GET and HTTP POST, SOAP serves as a mechanism for passing messages between the clients and servers. In this context, the clients are Web Services consumers, and the servers are the Web Services. The clients simply send an XML-formatted request message to the server to get the service. The server responds by sending back yet another XML-formatted message. The SOAP specification describes the format of these XML requests and responses. It is simple, yet it is extensible, because it is based on XML.

SOAP is different than HTTP GET and HTTP POST because it uses XML to format its payload. The messages being sent back and forth have a better structure and can convey more complex information compared to simple name/value pairs in HTTP GET/POST protocols. Another difference is that SOAP can be used on top of other transport protocols, such as SMTP in addition to HTTP.

Web Services Description (WSDL)

For Web Service clients to understand how to interact with a Web Service, there must be a description of the method calls, or the interface that the Web Service supports. This Web Service description document is found in an XML schema called WSDL (Web Services Description Language). Remember that type libraries and IDL scripts are used to describe a COM component. Both IDL and WSDL files describe an interface's method calls and the list of in and out parameters for the particular call. The only major difference between the two description languages is that all descriptions in the WSDL file are done in XML.

In theory, any WSDL-capable SOAP client can use the WSDL file to get a description of your Web Service. It can then use the information contained in that file to understand the interface and invoke your Web Service's methods.

WSDL Structure

The root of any Web Service description file is the <definitions> element. Within this element, the following elements provide both the abstract and concrete description of the service:

A container for datatype definitions.

An abstract, typed definition of the data being exchanged between the Web Service providers and consumers. Each web method has two messages: input and output. The input describes the parameters for the web method; the output describes the return data from the web method. Each message contains zero or more <part> parameters. Each parameter associates with a concrete type defined in the <types> container element.

Port type
An abstract set of operations supported by one or more endpoints.

An abstract description of an action supported by the service. Each operation specifies the input and output messages defined as <message> elements.

A concrete protocol and data-format specification for a particular port type. Similar to port type, the binding contains operations, as well as the input and output for each operation. The main difference is that with binding, we are now talking about actual transport type and how the input and output are formatted.

A collection of network endpoints--ports. Each of the Web Service wire formats defined earlier constitutes a port of the service (HTTP GET, HTTP POST, and SOAP ports).

A single endpoint defined by associating a binding and a network address. In other words, it describes the protocol and data-format specification to be used as well as the network address of where the Web Service clients can bind to for the service.

The following shows a typical WSDL file structure:

<definitions name="" targetNamespace="" xmlns:...>


  <message name="">...</message>

  <portType name="">
    <operation name="">
      <input message="" />
      <output message="" />

  <binding name="">
    <protocol:binding ...>
    <operation name="">
      <protocol:operation ...>

  <service name="">
    <port name="" binding="">
      <protocol:address location="" />

The <types> element contains physical type descriptions defined in XML Schema (XSD). These types are being referred to from the <message> elements.

For each of the web methods in the Web Service, there are two messages defined for a particular port: input and output. This means if a Web Service supports all three protocols: SOAP, HTTP GET, and HTTP POST, there will be six <message> elements defined, one pair for each port. The naming convention used by the Microsoft .NET autogenerated WSDL is:

MethodName + Protocol + {In, Out}

For example, a web method called GetBooks( ) has the following messages:

<message name="GetBooksSoapIn">...</message>
<message name="GetBooksSoapOut">...</message>
<message name="GetBooksHttpGetIn">...</message>
<message name="GetBooksHttpGetOut">...</message>
<message name="GetBooksHttpPostIn">...</message>
<message name="GetBooksHttpPostOut">...</message>

For each protocol that the Web Service supports, there is one <portType> element defined. Within each <portType> element, all operations are specified as <operation> elements. The naming convention for the port type is:

WebServiceName + Protocol

To continue our example, here are the port types associated with the Web Service that we build later in this chapter, PubsWS:

<portType name="PubsWSSoap">
  <operation name="GetBooks">
    <input message="GetBooksSoapIn" />
    <output message="GetBooksSoapOut" />

<portType name="PubsWSHttpGet">
  <operation name="GetBooks">
    <input message="GetBooksHttpGetIn" />
    <output message="GetBooksHttpGetOut" />
<portType name="PubsWSHttpPost">
  <operation name="GetBooks">
    <input message="GetBooksHttpPostIn" />
    <output message="GetBooksHttpPostOut" />

We have removed namespaces from the example to make it easier to read.

While the port types are abstract operations for each port, the bindings provide concrete information on what protocol is being used, how the data is being transported, and where the service is located. Again, there is a <binding> element for each protocol supported by the Web Service:

<binding name="PubsWSSoap" type="s0:PubsWSSoap">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http" 
                style="document" />
  <operation name="GetBooks">
    <soap:operation soapAction="http://tempuri.org/GetBooks"
                    style="document" />
      <soap:body use="literal" />
      <soap:body use="literal" />
<binding name="PubsWSHttpGet" type="s0:PubsWSHttpGet">
  <http:binding verb="GET" />
  <operation name="GetBooks">
    <http:operation location="/GetBooks" />
      <http:urlEncoded />
      <mime:mimeXml part="Body" />
<binding name="PubsWSHttpPost" type="s0:PubsWSHttpPost">
  <http:binding verb="POST" />
  <operation name="GetBooks">
    <http:operation location="/GetBooks" />
      <mime:content type="application/x-www-form-urlencoded" />
      <mime:mimeXml part="Body" />

For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of HTTP protocol. The <soap:operation> element defines the HTTP header soapAction, which points to the web method. Both input and output of the SOAP call are SOAP messages.

For the HTTP GET and HTTP POST protocols, the binding is <http:binding> with the verb being GET and POST, respectively. Because the GET and POST verbs are part of the HTTP protocol, there is no need for the extended HTTP header (like soapAction for SOAP protocol). The only thing we need is the URL that points to the web method; in this case, the <soap:operation> element contains the attribute location, which is set to /GetBooks.

The only real difference between the HTTP GET and POST protocols is the way the parameters are passed to the web server. HTTP GET sends the parameters in the query string, while HTTP POST sends the parameters in the form data. This difference is reflected in the <input> elements of the operation GetBooks for the two HTTP protocols. For the HTTP GET protocol, the input is specified as <http:urlEncoded />, whereas for the HTTP POST protocol, the input is <mime:content type="application/x-www-form-urlencoded" />.

Looking back at the template of the WSDL document, we see that the only thing left to discuss is the <service> element, which defines the ports supported by this Web Service. For each of the supported protocol, there is one <port> element:

<service name="PubsWS">
  <port name="PubsWSSoap" binding="s0:PubsWSSoap">
      location="http://.../PubsWs.asmx" />
  <port name="PubsWSHttpGet" binding="s0:PubsWSHttpGet">
      location="http://.../PubsWs.asmx" />
  <port name="PubsWSHttpPost" binding="s0:PubsWSHttpPost">
      location="http://.../PubsWs.asmx" />

Even though the three different ports look similar, their binding attributes associate the address of the service with a binding element defined earlier. Web Service clients now have enough information on where to access the service, through which port to access the Web Service method, and how the communication messages are defined.

Although it is possible to read the WSDL and manually construct the HTTP[1] conversation with the server to get to a particular Web Service, there are tools that autogenerate client-side proxy source code to do the same thing. We show such a tool in "Web Services Consumers" later in this chapter.

Web Services Discovery

Even though advertising of a Web Service is important, it is optional. Web services can be private as well as public. Depending on the business model, some business-to-business (B2B) services would not normally be advertised publicly. Instead, the Web Service owners would provide specific instructions on accessing and using their service only to the business partner.

To advertise Web Services publicly, authors post discovery files on the Internet. Potential Web Services clients can browse to these files for information about how to use the Web Services--the WSDL. Think of it as the yellow pages for the Web Service. All it does is point you to where the actual Web Services reside and to the description of those Web Services.

The process of looking up a service and checking out the service description is called Web Service discovery. There are two ways of advertising the service: static and dynamic. In both of these, XML conveys the locations of Web Services.

Static discovery

Static discovery is easier to understand because it is explicit in nature. If you want to advertise your Web Service, you must explicitly create the .disco discovery file and point it to the WSDL.[2] All .disco files contain a root element discovery as shown in the following code sample. Note that discovery is in the namespace http://schemas.xmlsoap.org/disco/, which is referred to as disco in this sample.

<?xml version="1.0" ?>
<disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco/">

Inside the discovery element, there can be one or more of contractRef or discoveryRef elements. Both of these elements are described in the namespace http://schemas.xmlsoap.org/disco/scl/. The contractRef tag is used to reference an actual Web Service URL that would return the WSDL or the description of the actual Web Service contract. The discoveryRef tag, on the other hand, references another discovery document.

This XML document contains a link to one Web Service and a link to another discovery document:

<?xml version="1.0" ?>
<scl:contractRef ref="http://yourWebServer/yourWebService.asmx?WSDL"/>
<scl:discoveryRef ref="http://yourBrotherSite/hisWebServiceDirectory.disco"/>

This sample disco file specifies two different namespaces: disco, which is a nickname for the namespace http://schemas.xmlsoap.org/disco/; and scl, short for http://schemas.xmlsoap.org/disco/scl/. The contractRef element specifies the URL where yourWebService WSDL can be obtained. Right below that is the discoveryRef element, which links to the discovery file on yourBrotherSite web site. This linkage allows for structuring networks of related discovery documents.

Dynamic discovery

As opposed to explicitly specifying the URL for all Web Services your site supports, you can enable dynamic discovery, which enables all Web Services underneath a specific URL on your web site to be listed automatically. For your web site, you might want to group related Web Services under many different directories and then provide a single dynamic discovery file in each of the directory. The root tag of the dynamic discovery file is dynamicDiscovery instead of discovery.

<?xml version="1.0" encoding="utf-8"?>
<dynamicDiscovery xmlns="urn://schemas-dynamic:disco.2000-03-17" />

You can optionally specify exclude paths so that the dynamic mechanism does not have to look for Web Services in all subdirectories underneath the location of the dynamic discovery file. Exclude paths are in the following form:

<exclude path="pathname" />

If you run IIS as your web server, you'd probably have something like the following for a dynamic discovery file:[3]

<?xml version="1.0" encoding="utf-8"?>
<dynamicDiscovery xmlns="urn://schemas-dynamic:disco.2000-03-17">
    <exclude path="_vti_cnf" />
    <exclude path="_vti_pvt" />
    <exclude path="_vti_log" />
    <exclude path="_vti_script" />
    <exclude path="_vti_txt" />
    <exclude path="Web References" />

Discovery setting in practice

A combination of dynamic and static discovery makes a very flexible configuration. For example, you can provide static discovery documents at each of the directories that contain Web Services. At the root of the web server, provide a dynamic discovery document with links to all static discovery documents in all subdirectories. To exclude Web Services from public viewing, provide the exclude argument to XML nodes to exclude their directories from the dynamic discovery document.


Universal Description, Discovery, and Integration (UDDI) Business Registry is like a yellow pages of Web Services. It allows businesses to publish their services and locate Web Services published by partner organizations so that they can conduct transactions quickly, easily, and dynamically with their trading partner.

Through UDDI APIs, businesses can find services over the web that match their criteria (e.g., cheapest fare), that offer the service they request (e.g., delivery on Sunday), and so on. Currently backed by software giants such as Microsoft, IBM, and Ariba, UDDI is important to Web Services because it enables access to businesses from a single place.

The System.Web.Services Namespace

Now that we have run through the basic framework of Microsoft .NET Web Services, let us take a look inside what the .NET SDK provides us in the System.Web.Services namespace.

There are only a handful of classes in the System.Web.Services namespace and the most important ones for general use are:

The base class for all Web Services.

An attribute that can be associated with a Web Service-derived class.

An attribute that can be associated with public methods within a Web Service-derived class.

The two essential classes for creating Web Services are the WebService base class and WebMethodAttribute. We make use of these classes in the next section, where we implement a Web Service provider and several Web Service consumers. WebService is the base class from which all Web Services inherit. It provides properties inherent to legacy ASP programming such as Application, Server, Session, and a new property, Context, which now includes Request and Response.

The WebMethodAttribute class allows you to apply attributes to each public method of your Web Service. Using this class, you can assign specific values to the following attributes: description, session state enabling flag, message name, and transaction mode. See the following section for an example of attribute setting in C# and VB.

The WebServiceAttribute class is used to provide more attributes about the Web Service itself. You can display a description of the Web Service, as well as the namespace to which this Web Service belongs.

In the next installement, you will learn about Web services providers and more.

View catalog information for .NET Framework Essentials, 2nd Ed.

Return to the .NET DevCenter.

Copyright © 2009 O'Reilly Media, Inc.