How to Use the webmethod attribute in ASP. NET WebService

Source: Internet
Author: User
How to: Use webmethod attributes

 

SetWebmethodAttribute appendedPublicMethod indicates that you want to expose this method as part of XML Web Services. You can also use the property of this attribute to further configure the behavior of the XML Web Services method. For more information, see the code model of XML Web Services in managed code.

The webmethod attribute provides the following attributes ):

    • Bufferresponse

    • Cacheduration

    • Description

    • Enablesession

    • Messagename

    • Transactionoption

Bufferresponse

WebmethodAttributeBufferresponseProperty enables caching of XML Web Services method responses. When setTrue(Default), ASP. NET caches the entire response before sending the response to the client. The buffer is very effective. It helps improve performance by minimizing the communication between the auxiliary process and the IIS process. When setFalseASP. NET caches responses in 16 KB blocks. Generally, this property is setFalse. For example, if you are writing a set, the set is outputting its items from the database as a stream. Unless otherwise specified, the default value isTrue. For more information, see webmethodattrise. bufferresponse attributes (property ).

Buffered XML Web Services method response
  • UseWebmethodAttributeBufferresponseProperties are as follows:

    Copy code in Visual Basic
    Public ClassService1InheritsSystem. Web. Services. WebService <system. Web. Services. webmethod (bufferresponse: = false)> _Public FunctionGetbigdata ()AsDataset'Implementation codeEnd FunctionEnd Class

     

    C # copy code
    Public ClassService1: system. Web. Services. WebService {[system. Web. Services. webmethod (bufferresponse =False)]PublicDataset getbigdata (){// Implementation code}}

Cacheduration

WebmethodAttributeCachedurationProperty enables caching of XML Web Services method results. ASP. NET caches the results of each unique parameter set. The value of this property specifies the number of seconds that ASP. NET will cache the result. If the value is zero, the result is disabled. Unless otherwise specified, the default value is zero. For more information, see webmethodattriation. cacheduration attributes (property ).

Cache the results of the XML Web Services Method
  • UseWebmethodAttributeCachedurationProperties are as follows:

    Copy code in Visual Basic
    Public ClassService1InheritsSystem. Web. Services. WebService <system. Web. Services. webmethod (cacheduration: = 60)> _Public FunctionConverttemperature (ByvalDfahrenheitAs Double)_As DoubleConverttemperature = (dfahrenheit-32) * 5)/9End FunctionEnd Class

     

    C # copy code
    Public ClassService1: system. Web. Services. WebService {[system. Web. Services. webmethod (cacheduration = 60)]PublicDouble converttemperature (double dfahrenheit ){Return(Dfahrenheit-32) * 5)/9 ;}}

Description

WebmethodAttributeDescriptionProperty provides a description of the XML Web Services method, which is displayed on the service help page. Unless otherwise specified, the default value is a null string. For more information, see webmethodattribute. Description attributes (property ).

Description of XML Web Services Methods
    • UseWebmethodAttributeDescriptionProperties are as follows:

      Copy code
      'Visual basicpublic 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 functionend 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

WebmethodAttributeEnablesessionProperty enables the session Status of the XML Web Services method. Once enabled, XML Web Services canHttpcontext. Current. SessionOr, if it is fromWebServiceIf the base class is inherited, you can useWebService. SessionTo access the session Status set. Unless otherwise specified, the default value isFalse. For more information, see webmethodattribute. enablesession attributes (property ).

Enable session Status in XML Web Services
  • UseWebmethodAttributeEnablesessionProperties are as follows:

    Copy code in 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 # copy code
     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

WebmethodAttributeMessagenameProperty enables XML Web Services to uniquely identify the overload method using aliases. Unless otherwise specified, the default value is the method name. WhenMessagenameThe result SOAP message will reflect the name instead of the actual method name. For more information, see webmethodattriename. messagename attributes (property ).

Provide the message name for the XML Web Services Method
  • UseWebmethodAttributeMessagenameProperties are as follows:

    Copy code in 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 # copy code
    Public ClassService1: system. Web. Services. WebService {[system. Web. Services. webmethod (messagename ="Adddoubles")]PublicDouble add (double dvalueone, double dvaluetwo ){ReturnDvalueone + dvaluetwo;} [system. Web. Services. webmethod (messagename ="Addintegers")]Public IntAdd (IntIvalueone,IntIvaluetwo ){ReturnIvalueone + ivaluetwo ;}}

    Add double-precision (Adddoubles) The method's SOAP request message will be similar to the followingCode:

    Copy code
    Post/mywebservice/service1.asmx HTTP/1.1 HOST: localhostcontent-type: text/XML; charset = utf-8Content-Length: lengthsoapaction: "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 okcontent-type: text/XML; charset = utf-8Content-Length: Length

    Add double-precision (Adddoubles) The soap Response Message of the method is similar to the following code:

    Copy code
    <? 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

WebmethodAttributeTransactionoptionProperty enables the XML Web Services method to participate as the root object of the transaction. Although you canTransactionoptionProperty is setTransactionoptionBut the XML Web Services method has only two possible behaviors: it is not involved in transactions (Disabled,Notsupported,SupportedOr it creates a new transaction (Required,Requiresnew). Unless otherwise specified, the default value isTransactionoption. Disabled. For more information, see webmethodattribute. transactionoption attributes (property ).

In addition to the prerequisites for any XML Web Services method, you also need to add a pairSystem. enterpriseservices. dll. The namespace contains the methods and properties of the Distributed Transaction Model publicly available in COM + services ).System. enterpriseservices. contextutilClassSetabortOrSetcompleteSelect the transaction method. For more information, see transactions and automatic transactions and XML Web Services in XML Web Services created using ASP. NET.

Use the XML Web Services method to create a new transaction
  1. Add a pairSystem. enterpriseservices. dll. For more information, see add and remove references.

  2. SetSystem. enterpriseservicesAdd the namespace to XML Web Services as follows:

    Copy code in Visual Basic
    ImportsSystem. enterpriseservices

     

    C # copy code
    UsingSystem. incluiseservices;
  3. UseWebmethodAttributeTransactionoptionProperties are as follows:

    Copy code in Visual Basic
    Public ClassService1InheritsSystem. Web. Services. WebService <system. Web. Services. webmethod (_ transactionoption: = transactionoption. requiresnew)> _Public FunctionDosomethingtransactional ()As String'The transaction was successful...Contextutil. setcomplete dosomethingtransactional = contextutil. transactionid. tostring ()End FunctionEnd Class

     

    C # copy code
      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 () ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.