Export (0) Print
Expand All

Using the WebMethod Attribute

Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service. You can also use the properties of this attribute to further configure the behavior of the XML Web service method. For more information, see Code Model for XML Web Services in Managed Code.

The WebMethod attribute provides the following properties:

BufferResponse

The BufferResponse property of the WebMethod attribute enables buffering of responses for an XML Web service method. When set to true, the default setting, ASP.NET buffers the entire response before sending it down to the client. The buffering is very efficient and helps improve performance by minimizing communication between the worker process and the IIS process. When set to false, ASP.NET buffers the response in chunks of 16KB. Typically, you would set this property to false only if you did not want the entire contents of the response in memory at once. For example, you are writing back a collection that is streaming its items out of a database. Unless otherwise specified, the default value is true. For more information, see WebMethodAttribute.BufferResponse Property.

To buffer the response of an XML Web service method

  • Use the BufferResponse property of the WebMethod attribute, as shown below:
    ' Visual Basic
    Public Class Service1
        Inherits System.Web.Services.WebService
        <System.Web.Services.WebMethod(BufferResponse:=False)> _
        Public Function GetBigData() As DataSet
            'implementation code
        End Function
    End Class
    
    // C#
    public class Service1 : System.Web.Services.WebService
    { 
        [System.Web.Services.WebMethod(BufferResponse=false)]
        public DataSet GetBigData()
        {
           //implementation code
        }
    }
    

CacheDuration

The CacheDuration property of the WebMethod attribute enables caching of the results for an XML Web service method. ASP.NET will cache the results for each unique parameter set. The value of this property specifies how many seconds ASP.NET should cache the results. A value of zero disables the caching of results. Unless otherwise specified, the default value is zero. For more information, see WebMethodAttribute.CacheDuration Property.

To cache the results of an XML Web service method

  • Use the CacheDuration property of the WebMethod attribute, as shown below:
    ' Visual Basic
    Public Class Service1
        Inherits System.Web.Services.WebService
        <System.Web.Services.WebMethod(CacheDuration:=60)> _
        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(CacheDuration=60)]
        public double ConvertTemperature(double dFahrenheit)
        {
           return ((dFahrenheit - 32) * 5) / 9;
        }
    }
    

Description

The Description property of the WebMethod attribute supplies a description for an XML Web service method that will appear on the Service help page. Unless otherwise specified, the default value is an empty string. For more information, see WebMethodAttribute.Description Property.

To supply a description for an XML Web service method

  • Use the Description property of the WebMethod attribute, as shown below:
    ' Visual Basic
    Public Class Service1
        Inherits System.Web.Services.WebService
        <System.Web.Services.WebMethod( _
           Description:="This method converts a temperature " & _
           "in degrees Fahrenheit to a temperature in degrees Celsius.")> _
        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(
           Description="Converts F to C a temperature in " +
           "degrees Fahrenheit to a temperature in degrees Celsius.")]
        public double ConvertTemperature(double dFahrenheit)
        {
           return ((dFahrenheit - 32) * 5) / 9;
        }
    }
    

EnableSession

The EnableSession property of the WebMethod attribute enables session state for an XML Web service method. Once enabled, 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. Unless otherwise specified, the default value is false. For more information, see WebMethodAttribute.EnableSession Property.

To enable session state in an XML Web service method

  • Use the EnableSession property of the WebMethod attribute, as shown below:
    ' Visual Basic
    Public Class Service1
        Inherits System.Web.Services.WebService
        <System.Web.Services.WebMethod(EnableSession:=True)> _
        Public Function ConvertTemperature(ByVal dFahrenheit As Double) _
                                           As Double
            Session("Conversions") = Session("Conversions") + 1
            ConvertTemperature = ((dFahrenheit - 32) * 5) / 9
        End Function
        <System.Web.Services.WebMethod(EnableSession:=True)> _
        Public Function GetNumberOfConversions() As Integer
            GetNumberOfConversions = Session("Conversions")
        End Function
    End Class
    
    // C#
    public class Service1 : System.Web.Services.WebService
    { 
        [System.Web.Services.WebMethod(EnableSession=true)]
        public double ConvertTemperature(double dFahrenheit)
        {
           Session["Conversions"] = (int) Session["Conversions"] + 1;
           return ((dFahrenheit - 32) * 5) / 9;
        }
        [System.Web.Services.WebMethod(EnableSession=true)]
        public int GetNumberOfConversions()
        {
           return (int) Session["Conversions"];
        }
    }
    

MessageName

The MessageName property of the WebMethod attribute 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 the MessageName, the resulting SOAP messages will reflect this name instead of the actual method name. For more information, see WebMethodAttribute.MessageName Property.

To supply a message name for an XML Web service method

  • Use the MessageName property of the WebMethod attribute, as shown below:
    ' Visual Basic
    Public Class Service1
        Inherits System.Web.Services.WebService
        <System.Web.Services.WebMethod(MessageName:="AddDoubles")> _
        Public Function Add(ByVal dValueOne As Double, _
                            ByVal dValueTwo As Double) As Double
            Add = dValueOne + dValueTwo
        End Function
        <System.Web.Services.WebMethod(MessageName:="AddIntegers")> _
        Public Function Add(ByVal iValueOne As Integer, _
                            ByVal iValueTwo As Integer) As Integer
            Add = iValueOne + iValueTwo
        End Function
    End Class
    
    // C#
    public class Service1 : System.Web.Services.WebService
    { 
        [System.Web.Services.WebMethod(MessageName="AddDoubles")]
        public double Add(double dValueOne, double dValueTwo)
        {
           return dValueOne + dValueTwo;
        }
        [System.Web.Services.WebMethod(MessageName="AddIntegers")]
        public int Add(int iValueOne, int iValueTwo)
        {
           return iValueOne + iValueTwo;
        }
    }
    

    The SOAP request message for the method that adds doubles, AddDoubles, will resemble the following:

    POST /myWebService/Service1.asmx HTTP/1.1
    Host: localhost
    Content-Type: text/xml; charset=utf-8
    Content-Length: length
    SOAPAction: "http://tempuri.org/AddDoubles"
    
    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <AddDoubles xmlns="http://tempuri.org/">
          <dValueOne>double</dValueOne>
          <dValueTwo>double</dValueTwo>
        </AddDoubles>
      </soap:Body>
    </soap:Envelope>
    HTTP/1.1 200 OK
    Content-Type: text/xml; charset=utf-8
    Content-Length: length
    

    The SOAP response message for the method that adds doubles, AddDoubles, will resemble the following:

    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <AddDoublesResponse xmlns="http://tempuri.org/">
          <AddDoublesResult>double</AddDoublesResult>
        </AddDoublesResponse>
      </soap:Body>
    </soap:Envelope>
    

TransactionOption

The TransactionOption property of the WebMethod attribute enables the XML Web service method to 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. For more information, see WebMethodAttribute.TransactionOption Property.

In addition to the prerequisites for any XML Web service method, 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. For more information, see Participating in Transactions in XML Web Services Created Using ASP.NET and Automatic Transactions and XML Web Services.

To create a new transaction with an XML Web service method

  1. Add a reference to System.EnterpriseServices.dll. For more information, see Adding and Removing References.
  2. Add the System.EnterpriseServices namespace to the XML Web service, as shown below:
    ' Visual Basic
    Imports System.EnterpriseServices
    
    // C#
    using System.EnterpriseServices;
    
  3. Use the TransactionOption property of the WebMethod attribute, as shown below:
    ' Visual Basic
    Public Class Service1
        Inherits System.Web.Services.WebService
        <System.Web.Services.WebMethod( _
           TransactionOption:=TransactionOption.RequiresNew)> _
        Public Function DoSomethingTransactional() As String
           'The transaction was successful...
           ContextUtil.SetComplete
           DoSomethingTransactional = ContextUtil.TransactionId.ToString()
        End Function
    End Class
    
    // C#
    public class Service1 : System.Web.Services.WebService
    { 
        [System.Web.Services.WebMethod(
           TransactionOption=TransactionOption.RequiresNew)]
        public string DoSomethingTransactional()
        {
           // The transaction was successful...
           ContextUtil.SetComplete();
           return ContextUtil.TransactionId.ToString();
        }
    }
    

See Also

Creating XML Web Services in Managed Code | WebMethodAttribute Class

Show:
© 2014 Microsoft