Export (0) Print
Expand All

Creating an XML Web Service Method

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. For more information, see Defining XML Web Service Methods.

The procedures below assume that you are working with public methods of a class that is the implementation of an XML Web service. For more information, see Code Model for XML Web Services in Managed Code.

To create an XML Web service method

  1. Select your .asmx file (for example, Service1.asmx) in Solution Explorer. On the View menu, click Code to view the code-behind file. Alternatively, right-click the .asmx file in Solution Explorer and then click View Code on the shortcut menu.
    Note   Solution Explorer hides code-behind files by default. Click Show All Files in the Solution Explorer toolbar to see hidden files. Alternatively, on the Project menu, click Show All Files.

    The .asmx file specifies the class that is the implementation of the XML Web service in the Class property of the .asmx file's WebService processing directive. Following is an example:

    ' Visual Basic
    <%@ WebService Language="vb" Codebehind="Service1.asmx.vb"
        Class="WebService1.Service1" %>
    
    // C#
    <%@ WebService Language="c#" Codebehind="Service1.asmx.cs" 
        Class="WebService1.Service1" %>
    

    If you rename the class, be sure to change the class name in the Class property of the WebService directive as well.

  2. Add a public method to the class specified in the Class property of the .asmx file's WebService processing directive as shown below:
    ' Visual Basic
    Public Class Service1
        Inherits System.Web.Services.WebService
        <System.Web.Services.WebMethod()> _
        Public Function ConvertTemperature(ByVal dFahrenheit As Double) _
                                           As Double
            ConvertTemperature = ((dFahrenheit - 32) * 5) / 9
        End Function
    End Class
    
    // C#
    public class Service1 : System.Web.Services.WebService
    { 
        [System.Web.Services.WebMethod()]
        public double ConvertTemperature(double dFahrenheit)
        {
           return ((dFahrenheit - 32) * 5) / 9;
        }
    }
    

    Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service. For more information, see Code Model for XML Web Services in Managed Code.

See Also

Creating XML Web Services in Managed Code | WebMethodAttribute Class

Show:
© 2014 Microsoft