Enabling RESTful Services with WCF

14 באוגוסט 2009

תגיות:
אין תגובות

I came across a number of sources that describe how to support RESTful Services with WCF, but unfortunately, I couldnt find one source that had all the small print. So, here it is – all in one place.

Objective

Let’s say you have a WCF Web Service exposed at an endpoint with this address: www.mycompany.com/Services/ProductsService.svc. And let’s say that in addition to speaking sophisticated SOAP with some clients you would also like to respond to GET requests from simple clients that need to retrieve all the information in XML (or JSON) form. For instance, you might like to respond to this URL: www.mycompany.com/productlist.xml with the contents of the productlist.xml file.

Solution

This is possible using WCF, and as you might expect, it involves defining an additional endpoint. There are actually three things you need to do:

  1. Define an additional end point using the webHttpBinding with a webHttp behavior.
  2. Add a ServiceContract with an OperationContract decorated with the [WebGet] attribute.
  3. Implement the OperationContract by returning a Stream with the contents of the required file.

1. Additional EndPoint with a webHttp Behavior

A configuration file is worth a thousand lines of code, so here is a rather minimilistic service-side configuration file that shows what you need.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <system.serviceModel>

    <services>

      <service name="ProductsService"

               behaviorConfiguration="ProductsServiceBehavior">

        <endpoint address="Services/ProductsService.svc"

                  binding="basicHttpBinding"

                  contract="IProductsService" />

        <endpoint address=""

                  binding="webHttpBinding"

                  behaviorConfiguration="WebBehavior"

                  contract="IRestfulOperations" />

        <host>

          <baseAddresses>

            <add baseAddress="http://www.mycompany.com/" />

          </baseAddresses>

        </host>

      </service>

    </services>

    <behaviors>

      <endpointBehaviors>

        <behavior name="WebBehavior">

          <webHttp />

        </behavior>

      </endpointBehaviors>

    </behaviors>

  </system.serviceModel>

</configuration>

2. Add an OperationContract with the [WebGet] Attribute

The code in this and the next section is based on responses by Carlos Figueira here.

Here is the new ServiceContract with the decorated OperationContract:

    [ServiceContract]

    public partial interface IRestfulMethods

    {

        [OperationContract, WebGet(UriTemplate = "/ProductList.xml")]

        Stream GetProductList();

    }

I advise you take a look at the documentation for more information on WebGet parameters. In particular, take a look at the UriTemplate which allows you to pass in parameters for the decorated method as part of the URL. WCF will extract the parameters and pass them as arguments to the method.

3. Implement the OperationContract

    public partial class ProductsService : IProductsService, IRestfulMethods

    {

        #region IRestfulMethods Members

 

        public Stream GetProductList()

        {

            string result = @"<?xml version=""1.0""?>

                <Products>

                    <Garden Chair>

                        <Quantity>2</Quantity>

                        <Price>100</Price>

                    <Garden Chair>

                    <Magic Wand>

                        <Quantity>1</Quantity>

                        <Price>50</Price>

                    </Magic Wand>

                </Products>";

            WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";

            return new MemoryStream(Encoding.UTF8.GetBytes(result));

        }

 

        #endregion

    }

For this to work you need to add a reference to the System.ServiceModel.Web assembly as well as to System.ServiceModel and to add a using statement for the System.ServiceModel.Web namespace.

Putting It All Together

Now, when a client makes a GET request to the URL www.mycompany.com/ProductList.xml, the new endpoint with the webHttpBinding responds by calling the GetProductList method. The GetProductList retrieves the data from the file (or generates it some other way), encapsulates it as a Stream and returns the Stream. WCF then writes the contents of the Stream to the HTTP Response.

Summary

In this post I demonstrated the three basic steps you need to implement to have a WCF service serve RESTful clients. You do this by mapping the RESTful requests to an OperationContract decorated with the WebGet attribute and that is exposed at an endpoint that uses the webHttpBinding binding with a webHttp behavior.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *