Building JSON,XML REST API using WCF services

Posted on

kick it on DotNetKicks.com

Recently Microsoft added REST support to WCF services.  So what RESTful service means?

From WIKI:

“A RESTFul web service is a simple web service implemented using HTTP and the principles of REST. Such a web service can be thought about as a collection of resources. The definition of such a web service can be thought of as comprising three aspects:

  • The URI for the web service such as http://example.com/resources/cars
  • The MIME type of the data supported by the web service. This is often JSON , XML or YAML but can be anything.
  • The set of operations supported by the web service using HTTP methods including but not limited to POST, GET, PUT and DELETE.

Members of the collection are addressed by ID using URIs of the form <baseURI>/<ID>. The ID can be any unique identifier. For example if a RESTFul web service representing a collection of cars for sale might have the URI http://example.com/resources/cars. If the service uses the car registration number as the ID then a particular car might be present in the collection as http://example.com/resources/cars/yxz123. “

In order to build simple REST service in Visual Studio you need to perform following steps:

 

Create new WCF service using “Add New Item” menu from solution explorer

I am going to have a service which will fetch all child records for selected record. Very common scenario for CRUD applications. IN VS2008 I am clicking on ‘Add New Item’ and Selecting WCF service. 

The system generate 3 files:

FetchChildItems.svc, this file contains a information what code should be executed by WCF when request is processed by IIS

<%@ ServiceHost Language="C#" Debug="true" Service="FetchChildItems" CodeBehind="~/App_Code/FetchChildItems.cs" %>

IFetchChildItems.cs contains your interface definitions:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
 
// NOTE: If you change the interface name "IFetchChildItems" here, you must also update the reference to "IFetchChildItems" in Web.config.
[ServiceContract]
public interface IFetchChildItems
{
    [OperationContract]
    void DoWork();
}
FetchChildItems.cs. contains empty implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
 
// NOTE: If you change the class name "FetchChildItems" here, you must also update the reference to "FetchChildItems" in Web.config.
public class FetchChildItems : IFetchChildItems
{
    public void DoWork()
    {
    }
}

Implementing a service and instructing it to return XML,JSON output

Next step you need to do is actually instruct your service to return your defined types in JSON or XML format.

In svc file you need to define what factory is processing WCF service request: 

<%@ ServiceHost Language="C#" Debug="true" Service="FetchChildItems" CodeBehind="~/App_Code/FetchChildItems.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>

WebServiceHostFactory factory that provides instances of WebServiceHost in managed hosting environments where the host instance is created dynamically in response to incoming messages.

In IFetchChildItems.cs you need to specify that service will be executed when consumer calls web url  endpoint. In order to do it you need to specify custom attribute WebInvoke (System.ServiceModel.Web namespace )

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
 
// NOTE: If you change the interface name "IFetchChildItems" here, you must also update the reference to "IFetchChildItems" in Web.config.
[ServiceContract]
public interface IFetchChildItems
{
    [OperationContract]
    [WebInvoke(
        Method = "GET",
        ResponseFormat = WebMessageFormat,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "{ID}/{Filter}")
        ]
    void DoWork(int ID, string Filter);
}

WebMessageFormat ResponseFormat is telling in what output type service will return response and it can be Json or Xml.
WebMessageBodyStyle BodyStyle is giving you ability to specify how your service response will be formatted
UriTemplate  allows you define your REST contract, WCF automatically extracts defined variables from URL and passing it values as parameters to service method

Defining Endpoint for REST WCF service in web.config

First you need to enable ASP.NET Compatibility Mode in serviceHostingEnvironment section:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
When ASP.NET Compatibility Mode is enabled WCF service works similar to asmx service and have access to HttpContext properties such as Session and etc.
 
Then you need to configure your service endpoint:
<service name="FetchChildItems">
    <endpoint address="" 
              binding="webHttpBinding" 
              behaviorConfiguration="FetchChildItemsBehavior" 
              contract="IFetchChildItems"
    />

Please note that binding attribute is set to binding=”webHttpBinding”

Behavior should include webHttp element

<behaviors>
            <endpointBehaviors>
                <behavior name="FetchChildItemsBehavior">
                    <webHttp />
                </behavior>
            </endpointBehaviors>            
        </behaviors>