Blog from Saravanan Arumugam

Let us talk about Technologies

Simple REST implementation with WebHttpBinding


REST – REpresentational State Transfer, is an architectural style for distributed communication. Here in this paper I am going to talk about the implementation of RESTful services in WCF.

 

A few bullet points about REST in WCF

WebHttpBinding was introduced in WCF with .Net Framework 3.5 to support REST.

  • REST based services can be simply called by an Http Url.
  • For example: http://localhost:8080/Calculator/Subtract?b=10&a=16 can call a WCF Operation called Subtract, with the parameters a and b.
  • Due its simplicity it is preferred in Internet based services (like Facebook, Twitter, MySpace etc.). However it doesn’t compromise on the security part. So it is still recommended for Enterprise services.

Well, the downsides are,

  • It won’t provide service side metadata. In other words, WebHttpBinding endpoint won’t show up in WSDL. But still the alternatives are evolving. Ref: WebHttpBinding not reaching the client
  • Because of this, we can say RESTful services are less decoupled from its clients. The client need to know all about the service implementation, operations contracts available and their parameters.
  • Doesn’t provide distributed transactions that Soap offers with WS-atomic standard.
    More detail can be seen in the following MSDN papers.

A Developer’s Guide to the WCF REST Starter Kit

More On REST (I personally like this paper a lot)

 

Steps for REST Implementation

Step 1: Add Reference

In order to use the REST based features, we must add reference to System.ServiceModel.Web. System.ServiceModel.Activation is needed for IIS hosting.

 

Step 2: Service and Operation Contracts

ServiceContract doesn’t need any change, but OperationContract need to be decorated with WebGetAttribute.

namespace TransactionPractice

{

    [ServiceContract()]

    public class CalculatorService

    {

        [WebGet(ResponseFormat = WebMessageFormat.Xml)]

        [OperationContract()]

        public long Add(int a, int b)

        {

            return (a + b);

        }

 

        [WebGet(ResponseFormat = WebMessageFormat.Xml)]

        [OperationContract()]

        public int Subtract(long a, int b)

        {

            return (int)(a – b);

        }

 

        [WebGet(ResponseFormat = WebMessageFormat.Xml)]

        [OperationContract()]

        public long Multiply(int a, int b)

        {

            return (a * b);

        }

 

        [WebGet(ResponseFormat = WebMessageFormat.Xml)]

        [OperationContract()]

        [FaultContract(typeof(string))]

        public double Division(long a, int b)

        {

            if (b == 0)

                throw new FaultException<string>("Divide by zero",

                 new FaultReason("Divide by zero attempted"));

 

            return (double)((double)a / b);

        }

    }

}

 

Here ResponseFormat is an optional named parameter. Json and Xml are the formats supported. I chose Xml since it is browser friendly. I am going to access these through the browser.

 

Step 3: Self Hosted applications – Binding and Endpoint behavior

For self host applications, we must make sure that we add the WebHttpBinding and a WebHttpBehavior to the end point. Here WebHttpBehavior enables the web programming model for the service.

The following code demonstrates this.

namespace CalculatorHost

{

    class Program

    {

        static void Main(string[] args)

        {

            ServiceHost host = new ServiceHost(typeof(CalculatorService),

                new Uri[] {});

 

            WebHttpBinding binding = new WebHttpBinding (WebHttpSecurityMode.None);

 

            ServiceEndpoint endPoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(CalculatorService)),

                binding, new EndpointAddress("http://localhost:8080/Calculator&quot;));

            WebHttpBehavior webBehavior = new WebHttpBehavior();

            endPoint.Behaviors.Add(webBehavior);

            host.AddServiceEndpoint(endPoint);

        

            host.Open();

            Console.WriteLine("Calculator Service Started!!!" +

                "\nPress enter to stop the service");

            Console.ReadLine();

            host.Close();

        }

    }

}

In the code we can notice that a regular ServiceHost is used. To be more specific, we can also use WebServiceHost (this is rather recommended).

Since WebServiceHost takes care of REST programming model WebHttpBehavior can be discounted from the code shown above.

A modified version of self host is shown below.

namespace CalculatorHost
{
    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(
                typeof(CalculatorService));
            WebHttpBinding binding = new WebHttpBinding(
                WebHttpSecurityMode.None);
            ServiceEndpoint endPoint = new ServiceEndpoint(
                ContractDescription.GetContract(
                    typeof(CalculatorService)),
                binding, new EndpointAddress(
                    "http://localhost:8080/Calculator"));
            host.AddServiceEndpoint(endPoint);
 
            host.Open();
            Console.WriteLine("Calculator Service Started!!!" +
                "\nPress enter to stop the service");
            Console.ReadLine();
            host.Close();
        }
    }
}

 

Step 3: IIS hosted applications – ServiceHost directive and Binding

For IIS hosted applications,

  • Add WebHttpBinding in configuration and
  • Edit the .svc file to add WebServiceHostFactory attribute in the ServiceHost directive.

The following code config snippet and ServiceHost directive demonstrate this.

    <services>
      <service name="DefaultService">
        <endpoint address="" 
         binding="webHttpBinding" 
         contract="CalculatorService" />
      </service>
    </services>

 

<%@ServiceHost Language="C#" Debug="true" 
Service="TransactionPractice.CalculatorService"  
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

 

 

Output

The URL http://localhost:8080/Calculator/Multiply?a=8&b=17 typed on browser produce the following output.

About these ads

4 responses to “Simple REST implementation with WebHttpBinding

  1. Francis August 29, 2011 at 2:35 pm

    Great article. Thanks!

  2. Pingback: WCF method returning JSON / XML objects not working | PHP Developer Resource

  3. vijay May 29, 2013 at 3:47 pm

    For the hosting I have added this to svc Factory=”System.ServiceModel.Activation.WebServiceHostFactory”
    Also in web.config file. My service still doesn’t return json for list. It was working great, suddenly stoped working.

  4. Steven Reed June 17, 2013 at 10:00 pm

    Your’s was the first example that I found that showed the ‘Service.svc’ file!

    Mine did not have the Factory=”System.ServiceModel.Activation.WebServiceHostFactory”, so was failing with various errors as I tried to figure out why it didn’t work.

    Thank you for posting a COMPLETE example.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 201 other followers

%d bloggers like this: