Export (0) Print
Expand All

Getting Started with XML Web Services in Visual Basic.NET and Visual C#

Visual Studio .NET 2003
 

Rob Caron
Visual Studio Team
Microsoft Corporation

October 2002

Summary: Microsoft® Visual Studio® .NET and XML Web services provide a simple, flexible, standards-based model that allows developers to assemble applications regardless of the platform, programming language, or object model. This article will help you get started creating and accessing XML Web services with Visual Basic .NET and Visual C#. (15 printed pages)

Contents

Introduction
Working With XML Web Services
Creating XML Web Services with Visual Studio
Deploying XML Web Services with Visual Studio
Accessing XML Web Services with Visual Studio
Conclusion

Introduction

An XML Web service is a programmable unit of software that can be accessed over the Internet and used remotely. An XML Web service can be used internally by a single application or exposed externally over the Internet for use by multiple applications. An XML Web service is accessible through a standard interface, allowing heterogeneous systems to work together as a single web of computation.

XML Web services depend heavily upon the broad acceptance of XML, HTTP, and other protocols that support interoperability. XML Web services use these standardized protocols to exchange data between systems that might otherwise be completely incompatible — for example, systems with different operating systems or component models. Developers can create applications that weave together XML Web services from a variety of sources in much the same way that they traditionally use components in a distributed application.

One of the core characteristics of an XML Web service is the high degree of abstraction between the implementation and consumption of a service. This abstraction allows XML Web services to be exposed and consumed without regard to their implementation. In other words, the only information that the Web service provider and client need to have in common is the inputs, outputs, and location of the Web service. Details such as programming language, hardware, operating system, or other implementation details are not necessary.

XML Web services are enabling a new era of distributed application development. XML Web services deliver interoperability on an entirely new level that is independent of platform, allowing different systems to seamlessly integrate their functionality. As the next revolutionary advancement of the Internet, XML Web services will become the fundamental structure that links together all computing devices. For more information, see Programming the Web with XML Web Services.

Working With XML Web Services

The ASP.NET page framework also serves as a framework for XML Web services in managed code. As such, XML Web services can access the many features of the .NET Framework, such as authentication, caching, and state management. Developers are then free to focus on creating or accessing XML Web services without needing to write infrastructure code.

In the ASP.NET application model, Web pages intended for the browser use the .aspx file extension. To differentiate XML Web services from regular ASP.NET pages, XML Web services use the .asmx extension.

XML Web services consist of an XML Web service entry point and the code that implements the XML Web service functionality. In ASP.NET, the .asmx file serves as the addressable entry point for the XML Web service. It references code in precompiled assemblies, a code-behind file, or code contained in the .asmx file itself.

There are two fundamental roles when working with XML Web services:

  • Creating an XML Web service — When you create an XML Web service, you are creating an application that exposes functionality to XML Web service clients.
  • Accessing an XML Web service — When you access an XML Web service, your client application locates, references, and uses the functionality contained within that XML Web service.

XML Web services can be either stand-alone applications or subcomponents of a larger Web application. The minimum requirement is that the client must be able to send messages to the XML Web service. For more information, see XML Web Services in Managed Code.

Creating XML Web Services with Visual Studio

To create XML Web services in managed code using Visual Studio, you need access to a Web server configured for developing ASP.NET applications. There are several types of Web projects; when you want to work with XML Web services using managed code in Visual Studio .NET, you use the ASP.NET Web Service project template. After you create an XML Web service project in Visual Studio, you see the Component Designer. The Component Designer is the design surface for your XML Web service. You can use the Design view to add components to your XML Web service, and the Code view to view and edit the code associated with your XML Web service.

When you create an ASP.NET Web Service project in Visual Studio, it constructs a Web application project structure on the Web server and a Visual Studio solution file on your local computer. The solution file (.sln) contains the configuration and build settings and keeps a list of files associated with the project. In addition, Visual Studio automatically creates the necessary files and references to support an XML Web service. When completed, the Visual Studio integrated development environment (IDE) displays the .asmx file in Design view.

By default, Visual Studio uses code-behind files, such as Service1.asmx.vb or Service1.asmx.cs, when you create an XML Web service with the ASP.NET Web Service project template. The code-behind file contains the code that implements the functionality of the XML Web service. By default, this code-behind file is hidden in Solution Explorer. When viewing the Code view of the .asmx file, you are actually seeing the contents of this code-behind file. The .asmx file itself contains a processing directive, WebService, which indicates where to find the implementation of the XML Web service. When you build an XML Web service in managed code, ASP.NET automatically provides the infrastructure and handles the processing of XML Web service requests and responses, including the parsing and creation of SOAP messages. The compiled output is a .dll file that is placed in the project's bin folder. For more information, see Creating XML Web Services in Managed Code.

WebService Processing Directive

The WebService processing directive provides necessary information to the ASP.NET environment, such as which class implements the XML Web service functionality. An example of the WebService processing directive in an .asmx file follows:

' Visual Basic
<%@ WebService Language="vb" Codebehind="Service1.asmx.vb"
    Class="WebService1.Service1" %>

// C#
<%@ WebService Language="c#" Codebehind="Service1.asmx.cs"
    Class="WebService1.Service1" %>
Note   To view the contents of the .asmx file, in Solution Explorer, right-click the .asmx file and click Open With on the shortcut menu. In the Open With dialog box, select Source Code (Text) Editor, and then click Open.

The Language attribute indicates the programming language used to develop the XML Web service. You can create XML Web services in any .NET-compatible language, such as Visual Basic .NET or Visual C#. The code-behind file associated with the .asmx page is indicated using the Codebehind attribute. The Class attribute indicates which class in the code-behind file implements the functionality of the XML Web service. For more information, see Code Model for XML Web Services in Managed Code.

System.Web.Services.WebService Class

The System.Web.Services.WebService class, which defines the optional base class for XML Web services, provides direct access to common ASP.NET objects, such as those for application and session state. By default, XML Web services created in managed code using Visual Studio inherit from this class. The XML Web service can inherit from this class to gain access to ASP.NET's intrinsic objects, such as Request and Session.

If the XML Web service does not inherit from the System.Web.Services.WebService class, it can still access the ASP.NET intrinsic objects from System.Web.HttpContext.Current. The class implementing the XML Web service must be public and must have a public default constructor (a constructor without parameters). This makes it possible for ASP.NET to create an instance of the XML Web service class to process incoming XML Web service requests. For more information, see Inheriting from the WebService Class.

WebService Attribute

Each XML Web service requires a unique namespace, which makes it possible for client applications to differentiate among XML Web services that might use the same method name. The default namespace for XML Web services created in Visual Studio .NET is "http://tempuri.org/". Although the namespace resembles a typical URL, you should not assume that it is viewable in a Web browser, it is merely a unique identifier.

Note   You may want to provide a Web page at that location that contains information about XML Web services you provide.

The WebService attribute provides the following properties:

  • Description – The value of this property contains a descriptive message that 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 – The value of this property contains the name for the XML Web service. By default, the value is the name of the class implementing the XML Web service. The Name property identifies the local part of the XML qualified name for the XML Web service. The Name property is also used to display the name of the XML Web service on the service help page.
  • Namespace – The value of this property contains the default namespace for the XML Web service. XML namespaces offer a way to create names in an XML document that are identified by a Uniform Resource Identifier (URI). By using XML namespaces you can uniquely identify elements or attributes in a XML document. So, within the service description for an XML Web service, Namespace is used as the default namespace for XML elements directly pertaining to that XML Web service. If not specified, the default namespace is used, http://tempuri.org/.

The following code demonstrates the use of the WebService attribute:

' Visual Basic
<WebService(Namespace:="http://MyServer/MyWebServices/", _
   Description:="Some descriptive text could go here.", _
   Name:="MyFavoritesService")> _
Public Class Service1
    Inherits System.Web.Services.WebService
    ' Implementation code.
End Class

// C#
[WebService(Namespace="http://MyServer/MyWebServices/",
   Description="Some descriptive text could go here.",
   Name="MyFavoritesService")]
public class Service1 : System.Web.Services.WebService
{ 
    // Implementation code.
}

For more information, see Using the WebService Attribute.

WebMethod Attribute

When you create an XML Web service in managed code, you indicate the methods that are available through that XML Web service by placing the WebMethod attribute before the method declaration of a Public method. Private methods cannot serve as the entry point for an XML Web service, although they can be in the same class and the XML Web service code can call them. The WebMethod attribute must be applied to each public method that is available as part of the XML Web service.

The WebMethod attribute contains several properties for configuring the behavior of an XML Web service. For example, you can use this attribute to provide a brief description that will appear on the associated service help page.

The WebMethod attribute provides the following properties:

  • BufferResponse – When set to true, the default setting, ASP.NET buffers the entire response before sending it to the client. The buffering is very efficient and helps improve performance by minimizing communication between the worker process and the Internet Information Services (IIS) process. When set to false, ASP.NET buffers the response in chunks of 16 KB. Typically, you set this property to false only if you do not want the entire contents of the response in memory at one time. For example, you are writing back a collection that is streaming its items out of a database.
  • CacheDuration – Specifies for how many seconds ASP.NET should cache the results for each unique parameter set. The default value is zero, which disables the caching of results.
  • Description – Supplies a description for an XML Web service method, which appears on the service help page. The default value is an empty string.
  • EnableSession – When set to false, the default setting, ASP.NET cannot access the session state for an XML Web service method. When set to true, the XML Web service can access the session state collection directly from HttpContext.Current.Session or with the WebService.Session property if it inherits from the WebService base class.
  • MessageName – Enables the XML Web service to uniquely identify overloaded methods using an alias. Unless otherwise specified, the default value is the method name. When specifying a value for MessageName, the resulting SOAP messages will reflect this name instead of the actual method name.
  • TransactionOption – Specifies whether the XML Web service method can participate as the root object of a transaction. Even though you can set the TransactionOption property to any of the values of the TransactionOption enumeration, an XML Web service method only has two possible behaviors; it does not participate in a transaction (Disabled, NotSupported, Supported), or it creates a new transaction (Required, RequiresNew). Unless otherwise specified, the default value is TransactionOption.Disabled. To use this property, you need to add a reference to System.EnterpriseServices.dll. This namespace contains methods and properties that expose the distributed transaction model found in COM+ services. The System.EnterpriseServices.ContextUtil class lets you vote on the transaction using the SetAbort or SetComplete methods.

The following code demonstrates the use of the WebMethod attribute:

' Visual Basic
Public Class Service1
    Inherits System.Web.Services.WebService
    <WebMethod(BufferResponse:=False, _
               CacheDuration:=60, _
               Description:="Some descriptive text",
               MessageName:="RetrieveData")> _
    Public Function GetBigChunkOfData() As DataSet
        ' Implementation code.
    End Function
End Class

// C#
public class Service1 : System.Web.Services.WebService
{ 
    [WebMethod(BufferResponse=false,
               CacheDuration=60,
               Description="Some descriptive text",
               MessageName="RetrieveData")]
    public DataSet GetBigChunkOfData()
    {
       // Implementation code.
    }
}

For more information, see Using the WebMethod Attribute.

Deploying XML Web Services with Visual Studio

When using Visual Studio .NET to create XML Web services in managed code, you use a standard deployment model: You compile your project and then you deploy the resulting files to a production server. The project .dll file contains the compiled code from the XML Web services code-behind class file (.asmx.vb or .asmx.cs) along with all other class files included in your project, but not the .asmx file itself. You then deploy this single project .dll file to the production server without any source code. When the XML Web service receives a request, the project .dll file is loaded and executed.

Figure 1. Deploying an XML Web Service

To deploy the XML Web service to a server other than the development server, you can add a Web Setup project or you can copy the required files to the destination server. To make your XML Web service available to others, you will need to deploy it to a Web server that is accessible to the clients you wish to support. For more information, see Deploying XML Web Services in Managed Code.

Service Help Page

When called from a Web browser without supplying a recognized query string, the .asmx file returns an automatically generated service help page for the XML Web service.

For example, to access the service help page for an XML Web service named Service1.asmx that is part of a project named WebService1 on your local machine, you use the following URL:

http://localhost/WebService1/Service1.asmx

This service help page provides a list of the methods the XML Web service provides and that you can access programmatically. Each method has a link that takes you to additional information about that method. In addition, this page contains a link to the XML Web service description document.

Figure 2. Service Help Page

The file name for the service help page is specified in the <wsdlHelpGenerator> XML element of a configuration file with a default setting of DefaultWsdlHelpGenerator.aspx. By default, this particular ASP.NET Web Form page is common to all XML Web services on that machine:

\%WINDOWS%
   \Microsoft.NET
      \Framework
         \[version]
            \CONFIG
               \DefaultWsdlHelpGenerator.aspx

Because the service help page is simply an ASP.NET Web Form, it can be replaced or modified to include items, such as a company logo. Alternatively, you can modify the <wsdlHelpGenerator> element of the associated web.config file to specify a custom service help page. For more information, see Configuration Options for XML Web Services Created Using ASP.NET.

Service Method Help Page

The service method help page provides additional information that relates to a particular XML Web service method. The page provides the ability to invoke the method using the HTTP-POST protocol. Subsequently, you cannot invoke methods that require complex types for input parameters, such as a dataset. In addition, the XML Web service method must support the HTTP-POST protocol to enable this functionality. At the bottom of the page, the service method help page provides sample request and response messages for the protocols the XML Web service method supports.

Figure 3. Service Method Help Page

For example, to access an XML Web service method named MyWebMethod on Service1.asmx that is part of a project named WebService1 on your local machine, you would use the following URL:

http://localhost/WebService1/Service1.asmx?op=MyWebMethod

For more information, see Exploring XML Web Service Content.

Web Service Description (.wsdl)

The service help page also provides a link to the XML Web service's service description, which is a formal definition of the XML Web service's capabilities. The service description is a document that uses the Web Services Description Language (WSDL) grammar. The service description defines the contract for the message formats that clients need to follow when exchanging messages with the XML Web service. For more information, see Web Services Description Language (WSDL) Explained.

XML Web Service Discovery

XML Web service discovery is the process of locating and interrogating XML Web service descriptions, which is a preliminary step for accessing an XML Web service. Through the discovery process, XML Web service clients can learn at design time that an XML Web service exists, what its capabilities are, and how to properly interact with it.

However, a Web site that implements an XML Web service need not support the discovery process. Instead, another site could be responsible for describing the service, such as an XML Web services directory. Alternatively, there may not be a public means of finding the service, such as in the case of a web service developed for use by an internal application. For more information, see XML Web Service Discovery.

Static Discovery (.disco)

You can enable programmatic discovery of an XML Web service by publishing a .disco file, which is an XML document that contains links to other discovery documents, XML Schemas, and service descriptions. XML Web services created using ASP.NET automatically can provide a generated discovery document. For example, to access the discovery document of an XML Web service named Service1.asmx that is part of a project named WebService1 on your local machine, use the following URL:

http://localhost/WebService1/Service1.asmx?DISCO

The following shows an example of the structure of a discovery document:

<?xml version="1.0" ?>
<disco:discovery  xmlns:disco="http://schemas.xmlsoap.org/disco"
xmlns:wsdl="http://schemas.xmlsoap.org/disco/wsdl">
      <wsdl:contractRef ref="http://MyWebServer/UserName.asmx?WSDL"/>
</disco:discovery>
Note   The discovery document is a container for elements that typically contain links (URLs) to resources that provide discovery information for an XML Web service. If the URLs are relative, they are assumed to be relative to the location of the discovery document.

For more information, see Fine-Tuning Discovery Mechanisms.

Web Service Directories

After deploying your XML Web service, you need to consider how to make it possible for developers to locate it if you intend for others to use it. An established method for advertising the availability of an XML Web service is to register it in a directory of XML Web services. The Universal Description, Discovery and Integration (UDDI) project provides a directory of businesses and the services they provide. For more information, see XML Web Services Directories.

Accessing XML Web Services with Visual Studio

An XML Web service client is any component or application that references and uses an XML Web service. This does not necessarily need to be a client-based application; in fact, in many cases your XML Web service clients might be other Web applications, such as Web Forms or even other XML Web services. When accessing XML Web services in managed code, a proxy class and the .NET Framework handle all of the infrastructure coding.

Accessing an XML Web service from managed code is a straightforward process. First, you add a Web reference to your project for the XML Web service you wish to access. The Web reference creates a proxy class with methods that serve as proxies for each exposed method of the XML Web service. Next, you add the namespace for the Web reference. Finally, you create an instance of the proxy class and then access the methods of that class as you would the methods of any other class.

For more information, see Accessing XML Web Services in Managed Code.

Locating an XML Web Service and Adding a Web Reference

Sometimes you may be both the provider and consumer of an XML Web service. In this case, you probably know the location and function of the XML Web service. At other times, you may be accessing an XML Web service provided by someone else. When this occurs, you may not even know if an XML Web service that suits your purposes in fact exists.

To simplify the coding model, applications written in managed code use a Web reference to represent each XML Web service locally. You add a Web reference to your project by using the Add Web Reference dialog box. This dialog box makes it possible for you to browse your local server, the Microsoft UDDI Directory, and the Internet at large for XML Web services.

The Add Web Reference dialog box uses the process of XML Web service discovery to locate eligible XML Web services on Web sites to which you navigate in the dialog box. For a given address, it will interrogate the Web site using an algorithm designed to locate XML Web service discovery (DISCO) documents and ultimately, XML Web service description documents that adhere to the grammar of the Web Services Description Language (WSDL).

After you have located an XML Web service for your application to access by using the Add Web Reference dialog box, clicking the Add Reference button instructs Visual Studio to download a copy of the service description to the local machine and then generate a proxy class for accessing the chosen XML Web service. The proxy class contains methods for calling each exposed XML Web service method both synchronously and asynchronously. For more information, see Locating XML Web Services.

Dynamic and Static URLs

A Web reference can use either a static URL or a dynamic URL. The Web Reference URL property of the Web reference is used to specify the URL of the referenced XML Web service. By default, this property is set to the URL of the XML Web service you selected, which is a static URL.

If you leave the URL Behavior property set to the default value of Static, the proxy class's URL property is set using a hard-coded URL when you create an instance of that class.

If you set the URL Behavior property of the Web reference to Dynamic, the application obtains the URL at run time from the <appSettings> section of your application's configuration file, such as:

<appSettings>
   <add key="myApplication.myServer.Service1"
        value="http://myServer/myXmlWebService/Service1.asmx"/>
</appSettings>

When you create an instance of a proxy object, you can also programmatically set the URL property of the object in your application. Regardless of which URL the proxy uses, it must be for an XML Web service that conforms to a WSDL that matches the one used when adding the Web reference. Otherwise, the proxy class that was generated earlier will not be able to interface with it.

Alternatively, you can generate a proxy class using the same tool (XML Web services Description Language Tool) used by Visual Studio to create a proxy class when adding a Web reference. This is necessary when you are unable to access the XML Web service from the machine on which Visual Studio is installed, such as when the XML Web service is located on a network that will not be accessible to the client until run time. You then manually add the file that the tool generated to your application project. For more information, see Managing Project Web References.

Using the Proxy Class

The generated proxy class has its own namespace associated with it, and you must add that namespace to your client application before you can create an instance of the proxy class. As with any other class, you must first create an instance of it before you can call any of its methods. This process does not differ at all from creating an instance of any other class.

When using a proxy class that Visual Studio generated directly from the service description of an XML Web service, accessing an XML Web service in managed code is a relatively simple process. To access an XML Web service method, your client application invokes either the corresponding synchronous method or asynchronous methods of the proxy object. These methods do the necessary work to remote the call over the wire to call the desired XML Web service method. By default, the proxy class uses SOAP to access the XML Web service method, as SOAP supports the richest set of data types of the three supported protocols (HTTP-GET, HTTP-POST, and HTTP-SOAP).

The proxy class generated by the Add Web Reference process derives from the System.Web.Service.Protocols.SoapHttpClientProtocol class, which contains several properties that you can use to control the behavior of how this class accesses an XML Web service.

In addition to others, the SoapHttpClientProtocol class provides the following properties:

  • ClientCertificates – This property allows a client to pass one or more client certificates, also known as Authenticode X.509 v.3 certificates, when calling an XML Web service method.
  • CookieContainer – If an XML Web service method uses session state, then a cookie is passed back in the response headers to the XML Web service client that uniquely identifies the session for that XML Web service client. For the XML Web service client to receive that cookie, a new instance of CookieContainer must be created and assigned to the CookieContainer property before calling the XML Web service method. This ensures that the cookie is properly included in subsequent requests.
  • Credentials – When using the Credentials property, an XML Web service client must instantiate a class implementing ICredentials, such as NetworkCredential, and then set the client credentials specific to the authentication mechanism. The NetworkCredential class can be used to set authentication credentials using the basic, digest, NTLM and Kerberos authentication mechanisms.
  • PreAuthenticate – When PreAuthenticate is true, the WWW-authenticate header is sent with the first request if the authentication mechanism supports doing so. When PreAuthenticate is false, the default value, a request is made to the XML Web service method without initially attempting to authenticate the user. If you know the Web service requires authentication, you can save one roundtrip by setting this property to true.
  • Proxy – Use this property if a client needs to use different proxy settings than those found in the system settings. You can use the WebProxy class to set the proxy settings, because it implements IWebProxy. Or, default proxy setting can be set in a configuration file.
  • Timeout – The time out, in milliseconds, for synchronous calls to the XML Web service. The default is 100000 milliseconds. Setting the Timeout property to Timeout.Infinite indicates that the request does not time out; however, the Web server can still cause the request to time out on the server side.
  • Url – The default value for this property is determined by the location attribute found in the service description from which the proxy class was generated.

For more information, see SoapHttpClientProtocol Class.

Calling XML Web Service Methods

After adding a Web reference to an XML Web service, you can invoke the exposed methods of that XML Web service and access the results just as you would any other method of a component.

In the example code below, the client application (Application1) is accessing an XML Web service for which it has a Web reference (Converter) that contains a proxy class (Service1), which has a method (ConvertTemperature) for calling the XML Web service. The two lines of code in bold represent the code that is necessary to access the XML Web service.

' Visual Basic
Imports System
Module Module1
    Sub Main()
        Dim cService As New Converter.Service1()
        Dim dFahrenheit As Double
        Dim dCelsius As Double
        Console.Write("Temperature in degrees Fahrenheit: ")
        dFahrenheit = Convert.ToDouble(Console.ReadLine())
        dCelsius = cService.ConvertTemperature(dFahrenheit)
        Console.Write("Temperature in degrees Celsius: ")
        Console.WriteLine(dCelsius.ToString())
    End Sub
End Module

// C#
using System;
namespace Application1
{
   class Class1
   {
      static void Main()
      {
         Converter.Service1 cService = new Converter.Service1();
         Console.WriteLine("Temperature in degrees Fahrenheit: ");
         double dFahrenheit = Convert.ToDouble(Console.ReadLine());
         double dCelsius = cService.ConvertTemperature(dFahrenheit);
         Console.Write("Temperature in degrees Celsius: ");
         Console.WriteLine(dCelsius.ToString());
      }
   }
}

For more information, see Accessing an XML Web Service in Managed Code.

Conclusion

XML Web services provide the ability to exchange messages in a loosely coupled environment using standard protocols such as HTTP, XML, SOAP, and WSDL. The messages can be structured and typed, or loosely defined. Because standard protocols serve as the basis for XML Web services, your XML Web service applications can communicate with a broad variety of implementations, platforms, and devices.

You create XML Web services using the ASP.NET page framework, which enables these XML Web services to access the many features of the .NET Framework. Because ASP.NET and the .NET Framework are the basis for XML Web services in managed code, developers can focus on creating or accessing XML Web services without needing to write infrastructure code.

Accessing an XML Web service in managed code is a relatively simple process when you use a proxy class that Visual Studio generated directly from the service description of the XML Web service. The proxy class does the work to transform the method call into a request message and the response message back into a method return value.

For step-by-step walkthroughs on how to create and access XML Web services in Visual Studio .NET, see Creating and Accessing XML Web Services Walkthroughs and Support WebCast: Microsoft .NET: Introduction to Web Services (http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com/servicedesks/webcasts/wc012902/wcblurb012902.asp).

Show:
© 2014 Microsoft