Building a Web Service


Sams Teach Yourself ASP.NET in 21 Days, Second Edition
By Chris Payne
Table of Contents
Day 16.  Creating XML Web Services

There are several steps to building a Web service, including building the actual functionality and the service description. The following sections will take you through each step with a simple Web service.

Building the Functionality

Web service files are essentially VB.NET or C# source files that end in an .asmx extension. A Web service, then, is represented by a class that derives from the WebService class. Listings 16.1 and 16.2 show a very simple Web service.

Listing 16.1 A Simple Web Service in VB.NET
 1:    <%@ WebService Language="VB"  %> 2: 3:    Imports System.Web.Services 4: 5:    public Class Calculator : Inherits WebService 6:       <WebMethod()> Public Function Add(intA As Integer, _ 7:          intB As Integer) As Integer 8:           Return(intA + intB) 9:       End Function 10:    End Class 
Listing 16.2 A Simple Web Service in C#
 1:    <%@ WebService Language="C#"  %> 2: 3:    using System.Web.Services; 4: 5:    public class Calculator : WebService { 6:       [WebMethod] public int Add(int intA, 7:          int intB) { 8:           return intA + intB; 9:       } 10:    } 


Save this file as c:\inetpub\wwwroot\tyaspnet21days\day16\Calculator. asmx (or calculator.cs.asmx). On line 1 you see the @ WebService directive, which is similar to the @ Page directive and declares that this file represents a Web service. This directive supports the familiar Language attribute, which you set to VB or C#. The directive also supports one other attribute, Class. This is the name of the Web service class that you're developing. In fact, on line 5 you see that the class name is indeed Calculator. A bit later, you'll learn about a neat feature of this attribute.

Next, you import the System.Web.Services namespace on line 3. This allows you to use all the necessary methods and classes of Web services. The class that you define on line 5 must inherit from the WebService class in this namespace.


You can have many classes in one .asmx file, but only one may be used for the Web service the one declared with the WebService directive at the top of the page.

Next, let's examine the only function in this class. The declaration for the Add method is pretty standard, with two notable items. The first is that the method must be declared public, meaning any other class or object can use it. If not, clients couldn't access this method of the Web service.

The second is the <WebMethod()> attribute, which tells ASP.NET that this method is available as a service to other applications. This is a very important attribute that must be present in order for clients to access methods, and you'll examine it a bit further later today in "The WebMethod Attribute."

Thus, methods that you want a client to access must be declared with Public and must contain the <WebMethod()> attribute.

Let's view this page in a browser. Figure 16.5 shows the output.

Figure 16.5. Viewing an .asmx file in a Web browser.


This is very interesting. What happened to the code? And where did the UI portion come from?

Like ASP.NET pages, .asmx files are compiled upon the first request. ASP.NET then serves up the service description whenever the page is requested. Figure 16.5, though in XML form, is what a client would see when he tries to access your service. The response tells the client the class name, Calculator, and the methods and properties that are publicly available for use. Click on Service Description on the right side of the page. This directs you to the same page with a querystring appended:


The WSDL tells ASP.NET that you want to see the service description in XML form. Figure 16.6 shows the XML for this service.

Figure 16.6. The XML service description for your Web service.


That's quite a bit of XML for one small Web service. This XML file uses a standard format called the Service Description Language (SDL) to tell clients what can be done with this service. We won't delve into this XML in any depth, but you should notice some familiar items. For instance, there's the following near the top of the output:

 1:    <s:element name="Add"> 2:       <s:complexType> 3:          <s:sequence> 4:             <s:element name="intA" type="s:int"/> 5:             <s:element name="intB" type="s:int"/> 6:          </s:sequence> 7:       </s:complexType> 8:    </s:element> 9:    <s:element name="AddResponse"> 10:       <s:complexType> 11:          <s:sequence> 12:             <s:element name="AddResult" type="s:int"/> 13:          </s:sequence> 14:       </s:complexType> 15:    </s:element> 


The first element describes your method, Add, and the parameters it takes. The second element describes the response from your method, aptly named AddResponse. The rest of the file describes how the Http-Get, Http-Post, and SOAP protocols should access this service.

Let's go back to the regular view of the .asmx file. Click the Add method and find out what else ASP.NET has in store for you. Figure 16.7 shows this page.

Figure 16.7. A detailed description of the Add method.


It's clear that there are a lot of parts to Web services. This page, known as the HTML description page, details a lot of interesting items and even lets you test out the method. Enter two values in the text boxes and click the Invoke button. A new window opens up with the XML-formatted answer. This is exactly the response a client would receive after calling this Web method. The next three sections of the page, SOAP, HTTP GET, and HTTP POST, show examples of the different methods that these protocols must use to access this Add method.

This page allows you to test your services. Note that because you're using a form to submit the data, you're using the Http-Post protocol to communicate with the service.

Enabling Discovery

Discovery is the process by which a client application finds a Web service and determines what it can do. This information is supplied by the service description, but most clients won't know (and shouldn't know) the filename of this description. Therefore, enabling discovery means giving clients links to these descriptions.

Discovery is enabled through .disco files for the Web service. These files are XML documents that contain links to descriptions of the service. Clients can access this file to figure out more about the available Web services.

Creating .disco files is simple. Listing 16.3 contains a sample discovery file for your calculator service.

Listing 16.3 The Discovery File for Your Calculator Service
 1:    <?xml version="1.0"?> 2:    <disco:discovery 3:       xmlns:disco="" 4:       xmlns:scl=""> 5:       <scl:contractRef ref="Calculator.asmx?WSDL"/> 6:    </disco:discovery> 


Save this file as calculator.disco. As you can see, this file is very simple because it only contains a link to the description of your service, shown on line 5. The additional namespaces provided by the xmlns tags specify the URLs (or namespaces) that define which valid names the scl and disco tags can use. In other words, the xmlns tags provide links to standard definitions of the scl and disco tags. Without these namespaces, your application won't know what to do with these extra tags.

The disco:discovery tag provides the links for a client to follow if he wants to find out about a Web service. These links can be to other .disco documents or to service descriptions. Service description links are provided with the scl tags, as shown on line 5. To provide a link to another .disco file, use the following syntax:

 <disco:discoveryRef ref="link" /> 

Request this file from your browser and you should see the same XML file.


The discovery file isn't necessary for clients to access Web services. If they know the proper URL, they can simply access the service description itself. Discovery documents only help anonymous clients find Web services that you want to make publicly available.

The WebMethod Attribute

Web services have methods just as regular classes and business objects do. However, only the methods marked with the WebMethod attribute (as shown on line 6 of Listing 16.1) are viewable to clients of the Web service. Recall from yesterday that only public variables are accessible to ASP.NET pages using a business object, while private methods are only viewable by the object itself. In the same way, WebMethod restricts access to clients.

Web methods act like regular class methods. They can interact with the ASP.NET Session or Cache objects (see Days 4, "Using ASP.NET Objects with C# and VB.NET," and 14, "Using ASP.NET's Improved Caching Capabilities"), they provide buffered responses just as ASP.NET pages do (Day 4), and they can interact with databases and data sources. In essence, they are exactly the same as regular class methods, with one, large, exception: They can be accessed over the Internet.

This is a very important concept. After all, the methods of a class are one of the most important parts; they represent how a user will interact with the class. Methods with the WebMethod attribute treat all callers as if they were local. In other words, there is no difference if you call a Web method from an ASP.NET page in the same directory as the .asmx file, or from another server halfway across the world. This attribute is the key that allows Web services to be usable by clients; let's examine it further. The WebMethod attribute has a lot of interesting features. It's represented by the WebMethodAttribute class, which operates just like any other .NET class, with properties and methods. Thus, when you insert the attribute as follows, you're actually creating a new instance of the WebMethodAttribute class:

 <WebMethod()> Public Function Add(intA As Integer) 

Assigning values for the properties of this class is a bit different from what you're used to. For example:

 'VB.NET_ <WebMethod(Description:="Adds two numbers")> Public Function Add(intA As Integer, intB As  graphics/ccc.gifInteger) //C# [WebMethod(Description="Adds two numbers")] public int Add(int intA, int intB) { 

You specify the property and value in the parentheses directly in the function declaration. Notice the colon before the equal sign in the VB.NET version this means that you're initializing a property, and not supplying parameters. If you simply used:

 <WebMethod(Description="Adds two numbers")> 

ASP.NET would think that Description="Adds two numbers" is the name of a variable that should be used to construct the WebMethod. This makes for an odd-looking function declaration, but it lets you set properties for this WebMethod. Multiple properties are separated by commas:

 <WebMethod(Description:="Adds two numbers", EnableSession:=False)>_ Public Function Add( graphics/ccc.gifintA As Integer, intB As Integer) 

Table 16.1 describes the properties you can set.

Table 16.1. WebMethod Properties
Property Description

Specifies whether or not to buffer the output from the Web service. The default value is true, which specifies that any generated response is buffered on the server before being sent to the client. The data is sent back in chunks.

If you're returning large amounts of data, it may be beneficial to set this property to false. This causes the data to stream to the client, providing slightly better performance. Otherwise, this property should always be true.


Web methods are cacheable, just as ASP.NET pages are. This property gives the number of seconds the response should be cached. The default is 0, meaning caching is disabled.

When this property is set to anything other than 0, the response is cached for that number of seconds and all subsequent calls to this method from the client will retrieve the data from the cache, rather than executing the method again.

When you're sending large amounts of data, this property should be enabled. See Day 14 for more caching suggestions.

Description This property provides a description of the Web method for clients. This description is viewable in the service description. The default value is String.Empty.
EnableSession Specifies whether or not session state is enabled for the current method. If this is enabled (which it is by default), you can use the Session object to store data. If you don't need to store any data in session variables, you may want to turn this option off. You'll receive an increase in performance.

This parameter is the name by which the Web method is called within the data that's sent to and from the service. By default, it's the same as the Web method's name.

This parameter is most often used to make method names unique. For instance, if you had two overloaded Add methods that each took different parameters, you could use MessageName to distinguish the methods. This property must be unique to the service description.


Like databases, Web services can also participate in transactions. Within a transaction, all code will be treated as a do-or-die situation. If one line fails, they all fail, and any changes that were made are rolled back. See Day 12, "Employing Advanced Data Techniques," for more information on transactions.

The possible values for this property are

Disabled Method runs without a transaction.

NotSupported No transaction support.

Supported Transactions are supported, but the method isn't run within one.

Required A transaction is required; creates a new transaction.

RequiresNew A transaction is required; creates a new transaction.

TypeID A unique ID to identify this attribute. Used to distinguish between two attributes that are of the same type.

Deploying Web Services

Deploying Web services is a simple matter. Since the Common Language Runtime handles all management of ASP.NET applications, just copy the appropriate .asmx files, .disco files, and custom business objects to the proper directories. Deploying applications has never been easier!

It's a common practice to include a web.config file for the directory containing the services (Day 18, "Configuring and Deploying ASP.NET Applications," will discuss this file in more detail). Often you'll want to implement security mechanisms for these services so that anonymous users don't come along and take advantage of your work. For example, if you develop a Web service for a company, it will most likely be used to generate revenue. If anyone could come along and use the service, the company would never make any money. Securing the Web service (as we'll learn about tomorrow) prevents this situation, and allows you to control who has access to your services.


The directory that you're deploying to must be flagged as an Internet Information Server (IIS) application directory. Otherwise, these services won't be executed and won't be exposed to clients.

Any directory you've created that allows ASP.NET pages to function is an IIS application directory.


    Sams Teach Yourself ASP. NET in 21 Days
    Sams Teach Yourself ASP.NET in 21 Days (2nd Edition)
    ISBN: 0672324458
    EAN: 2147483647
    Year: 2003
    Pages: 307
    Authors: Chris Payne

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: