Share via


How to: Access a Web Service in Managed Code

 Windows Communication Foundation Services and ADO.NET Data Services

Accessing a Web service from managed code is a straightforward process. First, you add a Web reference to your project for the 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 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 Code Model for Accessing Web Services in Managed Code.

By default, adding a Web reference also adds methods to the proxy class for accessing the Web service asynchronously. For more information, see How to: Access a Web Service Asynchronously in Managed Code.

To access a Web service in managed code

  1. Create the application from which you want to access a Web service. This application could even be another Web service.

  2. Add a Web reference for the Web service with which your application will interact. For instructions, see Adding and Removing Web References.

  3. Create an instance of the proxy object in your client code where you want to access the Web service.

  4. Access the methods of the Web service as you would any other component.

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

    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
    
    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());
          }
       }
    }
    

See Also

Other Resources

Accessing Web Services in Managed Code

Building XML Web Service Clients