Exposing a Web Service

only for RuBoard

Exposing the methods of a C# or Visual Basic .NET class as an ASP.NET web service is fairly simple. The code is written in a file that ends with the .asmx extension and published into a web virtual directory, just what you normally do with a .aspx page. Listing 11.1 provides a simple Calculator web service that exposes two methods, Add and Subtract , that add and subtract two integers respectively.

Listing 11.1 A Simple Inline Web Service ( Calculator.asmx )
 <%@ WebService  Language="C#"   Class="Calculator" %>  using System.Web.Services;  public class Calculator : WebService  {      [WebMethod]       public int Add(int a , int b)       {           return a + b;       }       [WebMethod]       public int Subtract(int a , int b)       {           return a - b;       }  } 

Adding the WebMethod attribute to a method within an XML Web Service makes the method callable from remote web clients . Methods within a class that have this attribute set are called web service methods . It's essential that the method and class are be defined as public.

A Visual Basic .NET web service uses the following syntax to add the WebMethod attribute:

 <WebMethod> Public Function Add( a as Integer, b as Integer ) as Integer 

Note

The WebMethod attribute is represented by the WebMethodAttribute class.


To expose your application logic, all that you need to do in the .asmx file is the following:

  • Add an @ WebService directive at the top of the page, just as you provide a directive at the top of a .aspx page (for example, @ Page ). The WebService directive supports two attributes, the Class that is required and an optional Language attribute. The Class attribute must be set to the name of the class, the methods and properties of which you want to expose as a web service. The .asmx file can have more than one class, but the class name assigned to the Class attribute in the directive at the top of the page alone can be used for the web service. By default, the Language attribute is set to VB (Visual Basic .NET). You can override that by setting it to any of the .NET languages (a language that provides a .NET compiler).

  • Include a reference to the System.Web.Services class.

  • Place the WebMethod attribute on any method or property you want to programmatically expose over the web.

  • Inherit the class from the WebService base class. You need to inherit from this class in order to get access to the ASP.NET intrinsics, which are the class' properties. These ASP.NET intrinsics , such as the Application , Context , Session , Server , and User properties, can be accessed through HttpContext . Therefore, it is not mandatory to inherit from the WebService class. This fact allows you to have your class inherited from another base class instead of the WebService class.

Again, similar to the .aspx pages, the .asmx files are compiled upon first request. Navigating to the URL for the web service without any parameters in a web browser, you can view the Service help page. By default, the Service help page contains information from the clients about how to communicate with the XML Web Service and the XML Web Service methods it exposes. The Service help page is simply an ASP.NET web form, named DefaultWsdlHelpGenerator.aspx . It's located in the [ system drive letter ]: \WINNT\Microsoft.NET\Framework\vx.x.xxx\CONFIG directory. Figure 11.1 shows the web service ( .asmx ) file, as viewed in a browser.

Figure 11.1. The . asmx file viewed in a browser.
graphics/11fig01.gif

You can modify or even replace the .asmx file to include other items, such as your company logo. If you want to change the filename, you must first change the default name specified in the <wsdlHelpGenerator> XML element of a configuration file ( machine.config ) in the same directory.

Testing the Web Service

You can test the web service in the browser using either HTTP-GET or HTTP-POST . Figure 11.2 shows the web service being tested by using the HTTP-GET method, which is the default.

Figure 11.2. Testing the web service.
graphics/11fig02.gif

Entering the appropriate values (for example, 4 and 5), and clicking the Invoke button displays the window shown in Figure 11.3 with the XML returned by the web service.

Figure 11.3. Result of invoking the add web method.
graphics/11fig03.gif

To test the web service using the HTTP-POST method, you must send the parameter values within the body of the HTTP request rather than the querystring, which is the case for the GET method. For this test, you can create an HTML page. The following code shows the form element in the HTML page to test to the Calculator web service:

 <form method=POST  action='http://localhost/WebServices/calculator/calculator.asmx/Add' >         <input type="text" size="5" name='a'></td> -        <input type="text" size="5" name='b'></td> =         <input type=submit value="Add" NAME="Submit1"> </td>     </form> 

Pay attention to the format of the action URL and also note that the names of the input text controls match the parameter names in the web service method. Alternatively, you can modify the DefaultWsdlHelpGenerator.aspx page to set the flag showPost to true.

In the ASP.NET web services, the details of serializing .NET data types into SOAP data types and deserializing the SOAP data types into .NET data types are hidden from the developer, which allows him to concentrate on the business logic rather than the plumbing involved. The framework also takes care of interpreting the SOAP requests from a remote client, invoking the appropriate web service method and sending back a SOAP response to the clients. The ISAPI listener aspnet_isapi.dll instantiates the Http Handler class System.Web.Services.Protocols.WebServiceHandlerFactory to process the requests for any .asmx files published on your web server. You can view an *.asmx file's path mapped to the WebServiceHandlerFactory class in the httpHandlers element in the machine.config file.

Apart from creating a help document and serializing and deserializing a SOAP request response, the Http Handler class also generates the WSDL files. The WSDL file is discussed in the section, "Consuming Web Services."

Using Code Behind with ASP.NET Web Services

Listing 11.1 showed the .asmx file with inline code as all the application logic is contained within the file. Just as ASP.NET web forms provide an option for code behind, the ASP.NET web services also provide an option to add the application logic in an external assembly. This assembly should be placed in the application's bin directory.

We create the web service .asmx file that contains nothing more than the WebService directive, the Class assigned the name of the web service class, and the Codebehind attribute, which is assigned the name of the code behind file. The following is a line of code contained in the Calculator_Codebehind.asmx file:

 <%@ WebService  Codebehind="Calulator.cs"   Class="Calculator" %> 

Listing 11.2 shows the code for the code behind class Calculator.

Listing 11.2 The Code Behind Calculator Class ( Calulator.cs )
 using System;  using System.Web;  using System.Web.Services;  public class Calculator : WebService  {      [WebMethod]       public int Add(int a , int b)       {           return a + b;       }       [WebMethod]       public int Subtract(int a , int b)       {           return a - b;       }  } 

You can compile this file into a .NET assembly by using the command-line compiler:

 csc /t:library /r:System.Web.dll /r:System.Web.Services.dll Calculator.cs 

You have to copy this assembly file into the bin directory before you can get your web service working. If you create your web service using Visual Studio .NET, by default, you will be using the code behind option. The advantage of using the code behind option is that the assembly can be used in other applications or ASP.NET pages.

The WebMethod Attribute

The WebMethod attribute supports some properties that you can set to make use of some features for a specific web service method, such as enabling session state management, buffering, and transactions.

You are probably familiar with some of these properties because they are similar to some of the Response object properties and the page directives in ASP.NET.

For example, the following TransactionOption property used with a web service method begins a new transaction when the method is called:

 [WebMethod(TransactionOption= TransactionOption.RequiresNew)] 

The following code line shows the syntax used for setting a description and enabling session state in a Visual Basic .NET web service method:

 <WebMethod(Description := "Adds two integers", EnableSession := True)> 

Table 11.1 lists all the public properties of the WebMethodAttribute class.

Table 11.1. Public Properties of the WebMethodAttribute Class

Property

Description

BufferResponse

Gets or sets whether the response for this request is buffered.

Setting BufferResponse to true buffers the response of the XML Web Service before being sent to the web service client.

When BufferResponse is false, the response to the XML Web Service method is sent back to the client as it is serialized. If the XML Web Service method returns large amounts of data to the client, it is recommended that you set BufferResponse to false because this consumes a large amount of the server memory. For smaller amounts of data, XML Web-Service performance is better with BufferResponse set to true. This property is set to true by default.

CacheDuration

Gets or sets the number of seconds the response should be held in the cache.

The default is 0, which means the response is not cached. When caching is enabled, requests and responses are held in memory on the server for at least the duration of the cache. You must not set this property if you expect requests or responses to be large, or if you expect requests to vary widely.

Description

A descriptive message that describes the XML Web Service method.

The descriptive message is displayed to prospective consumers of the XML Web Service when description documents for the XML Web Service are generated, such as the service description and the Service help page. The default value is String.Empty .

EnableSession

Indicates whether session state is enabled for an XML Web Service method.

If this is set to true, you can use the ASP.NET HttpSessionState object to store session state. If session state is not needed for an XML Web Service method, disabling it can improve performance.

MessageName

The name used for the XML Web Service method in the data passed to and returned from an XML Web Service method. The default is the name of the XML Web Service method.

If an XML Web Service contains two or more XML Web Service methods with the same name, you can uniquely identify the individual web service methods by setting the MessageName property to a name unique within the XML Web Service without changing the name of the actual method name in the code.

TransactionOption

Indicates the transaction support of an XML Web Service method. The default is TransactionOption.Disabled .

When the XML Web Service method is executed with a transaction, the code is treated as an atomic unit of work that either fails or succeeds as a whole. Each XML Web Service method participates in its own transaction because an XML Web Service method can only act as the root object in a transaction. The following are the possible values for this property:

TransactionOption.Disabled The web service method is executed without a transaction.

TransactionOption.NotSupported No transaction support. The web service method is executed without a transaction.

TransactionOption.Supported Transactions are supported but the web service method is executed without a transaction.

TransactionOption.Required The web service method requires a transaction. Because web service methods can only participate as the root object in a transaction, a new transaction will be created for the web service method.

TransactionOption.RequiresNew The web service method requires a new transaction. When a request is processed , the XML Web Service is created within a new transaction.

TypeId

When implemented in a derived class, TypeId gets a unique identifier for this attribute. It is intended that the unique identifier be used to distinguish between two attributes of the same type.

The WebService Attribute

Just as the WebMethod attribute supports properties for the methods in a web service, the WebService attribute supports properties to configure the properties for the WebService class. This attribute is represented by the WebServiceAttribute class.

The following code changes the default http://tempuri.org namespace for an ASP.NET web service:

 [WebService(Namespace="http://newriders.com/webservices/calculator")]  public class Calculator : WebService 

The following code line changes the name of the web service:

 <WebService(Name:="MyCalculatorService")> Public Class Calculator 

These changes are reflected in the Web Service help page and the WSDL that's generated.

Table 11.2 lists all the public properties of the WebServiceAttribute class.

Table 11.2. Public properties of the WebServiceAttribute class

Property

Description

Description

A descriptive message for the XML Web Service. The message is displayed to prospective consumers of the XML Web Service when description documents for the XML Web Service are generated, such as the service description and the Service help page.

Name

Gets or sets the name for the XML Web Service.The default value is the name of the class implementing the XML Web Service.

Namespace

Gets or sets the default XML namespace to use for the XML Web Service.

TypeId

When implemented in a derived class, gets a unique identifier for this attribute. It's intended that the unique identifier be used to distinguish between two attributes of the same type.

only for RuBoard


XML and ASP. NET
XML and ASP.NET
ISBN: B000H2MXOM
EAN: N/A
Year: 2005
Pages: 184

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net