WCF: WSDL and Contracts

Yesterday, I talked about building a simple Windows Communication Foundation client which communicated with an ASMX web service.  In that post, I mentioned that I used Add Web Reference to create the Indigo Proxy.  That tool reads the WSDL file from your service and, among other things, creates a contract.  I thought it might be useful to describe how  to manually create a contract based on the WSDL file.  It is actually pretty straightforward and aids in the understanding of WCF.

The easiest way to create a contract is to create an interface and decorate it with the [ServiceContract] attribute.  The name of the interface can be anything you want.  The methods signatures in the interface are associated with operations in the WSDL file.  You decorate the method with the [OperationContract] attribute.  This attribute contains parameters which you use to match it to the WSDL.  For example, assume you have the following WSDL:

<wsdl:operation name="MyAdd">

<soap:operation soapAction="**https://tempuri.org/MyAdd**" style="document" />

You could use the following:

[OperationContract (Name="MyAdd",Action="https://tempuri.org/MyAdd")]

Finally, you need to set the parameter names and types, along with the return type, based on the element names in the WSDL file. For example, assume the following element names in the WSDL file:

  <s:element name="MyAdd">

      <s:complexType>

            <s:sequence>

             <s:element minOccurs="1" maxOccurs="1" name="x" type="s:int" />

             <s:element minOccurs="1" maxOccurs="1" name="y" type="s:int" />

            </s:sequence>

      </s:complexType>

</s:element>

   

<s:element name="MyAddResponse">

      <s:complexType>

         <s:sequence>

          <s:element minOccurs="1" maxOccurs="1" name="MyAddResult" type="s:int" />

         </s:sequence>

      </s:complexType>

</s:element>

You can use this info to complete the contract, as follows:

[

ServiceContract]

public interface IMyService

{

[

OperationContract (Name="MyAdd",Action="https://tempuri.org/MyAdd")]

int NewAdd(int x, int y);

}

-David