Affecting your .Net SOAP message through attributes – level 300

With the .Net implementation of web services, you can design the schema of a web service call without having to author WSDL by hand.  I won’t discuss contract first here.  I recognize that many are happy with the default .Net implementation of a webservice.  It is possible to easily affect the Xml format of the SOAP envelope, however.  Mainly, you need to define the Xml structure of the SOAP envelope.  By default, .Net makes nodes with your parameter names, like so:


  146 [WebMethod]
  147 public int Foo(string firstParam, string secondParam) {return 0;}
POST /webservicetest/movie.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: “http://palermo.cc/Foo”

<?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>
<Foo xmlns=”http://palermo.cc”>
<firstParam>string</firstParam>
<secondParam>string</secondParam>
</Foo>
</soap:Body>
</soap:Envelope>

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?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>
<FooResponse xmlns=”http://palermo.cc”>
<FooResult>int</FooResult>
</FooResponse>
</soap:Body>
</soap:Envelope>



What if I don’t want to expose my naming conventions in my soap message?   Moreover, I have specific names that I want for the Soap message.  I can add XmlElement attributes to the parameters to customize the Soap message:


  148 [WebMethod]
  149 public int Foo(
  150     [XmlElement(“ProductCode”)] string firstParam,
  151     [XmlElement(“Quantity”)] string secondParam)
  152 {return 0;}

Here is the part of the SOAP message that is changed:


<?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>
    <Foo xmlns=”http://palermo.cc”>
      <ProductCode>string</ProductCode>
      <Quantity>string</Quantity>
    </Foo>
  </soap:Body>
</soap:Envelope>





Because .Net uses the XmlSerializer for Soap-object conversion, the service Xml schemas can be completely customized.  Another one of my favorite things is to return a object from a web service while ensuring the contract is explicit.  On my object, I implement ISerializable and define my format.