Develop and Consume WCF REST Service

This article shows a simple way of developing WCF REST Services and consuming them through JQuery in ASP.Net application.

What is REST?

REST – Representational State Transfer in an architectural style for designing network applications. The main idea behind is that rather using different mechanisms such as SOAP, CORBA, RPC to connect between systems, user can use simple HTTP to make calls between them. RESTful Services use HTTP requests to POST (modify or update) data, to DEL (delete) data or GET(retrieve) data.

What is JQuery?

jQuery is a coding language that is a branch from JavaScript. jQuery works like JavaScript where it’s used to help with interaction and effects with your development code.

You can find the complete tutorial of JQuery at http://docs.jquery.com/Tutorials:How_jQuery_Works

Let’s start the real Coding work.

Creating WCF Rest Service

  1. Open Visual Studio
  2. Create a WCF Service Application Project.
  3. Create a new Service Interface named as IRestServiceImpl.cs, following code snippet shows the complete code of this interface.

     

    namespace RestService

    {


    // NOTE: You can use the “Rename” command on the “Refactor” menu to change the interface name “IRestServiceImpl” in both code and config file together.

    [ServiceContract]


    public
    interface
    IRestServiceImpl

    {

    [OperationContract]

    [WebGet(ResponseFormat=WebMessageFormat.Xml, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate= “xml/{id}”)]


    string XMLData(string id);

     

    [OperationContract]

    [WebGet(ResponseFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate=“json/{id}”)]


    string JSONData(string id);

    }

    }

     

    In WCF all the web methods should be annotated with the OperationContract and the service class should be annotated with the ServiceContract. This is necessary for both SOAP based or REST based calls.

    Rest, as per the above code there are two WCF operation contracts; one returns data in XML and the other returns data in JSON. JSON data is more less in size as it does not contains tags and all that what xml have. Both the methods are annotated with WebGet attribute.
    In WCF for making REST based calls you need to annotate the method either using WebGet or WebInvoke to define specific mapping to the HTTP uniform interface. The reason Microsoft provided two attributes because GET requests are logically different from POST, DELETE, PUT etc. the bottom line is if you want to use HTTP GET you use WebGet otherwise WebInvoke for all others. Here as we are retrieving the data I have used WebGet.

     

    ResponseFormat tell what the format of the data that is travel back to client. There are two formats XML or JSON. UriTemplate helps to specify the template of REST calls over HTTP and the way method will be accessible from client in a REST way.

     

  4. Create a RestServiceImpl.cs class and implement IRestServiceImpl.cs interface. Following code shows the complete snippet of RestServiceImpl.cs

     

    namespace RestService

    {


    // NOTE: You can use the “Rename” command on the “Refactor” menu to change the class name “RestServiceImpl” in code, svc and config file together.


    public
    class
    RestServiceImpl : IRestServiceImpl

    {

     


    public
    string XMLData(string id)

    {


    return
    “you have typed=” + id;

    }

 


public
string JSONData(string id)

{


return
“you have typed=” + id;

}

}

}

 

Testing WCF Service

  1. Now just run the WCF Service Application and test. Below URL shows the way of making REST calls.

    For XML,

    http://localhost:31189/RestServiceImpl.svc/xml/123

    For JSON,

    http://localhost:31189/RestServiceImpl.svc/json/123

Creating ASP.Net Web Application

 

  1. Create ASP.Net web project to consume WCF REST service
  2. Open default.aspx page and add html text box and button

     

<input
id=”text” type=”text”/>

<input
id=”set” type=”button” value=”Click” onclick=”RetrieveVIAWCFREST();”/>

 

  1. Now define the function RetrieveVIAWCFREST under script tag

     

    <script>

     


    function RetrieveVIAWCFREST() {

     

    var textVal= $(‘#text’).val();

     

    $.ajax({

    type: “GET”,

    contentType: “application/json; charset=utf-8”,

    url: http://localhost:31189/RestServiceImpl.svc/json/&#8221;+textVal,

    dataType: “json”,

    processdata: false,

    success: function (data) {


    var result=data.JSONDataResult;

    alert(result);

    },

    error: function () { alert(“Not Done”); }

    });

     

    }

     


    </script>

     

.ajax is a JQuery function which helps the developer to transport the data from client server in a simple way. It calls XMLHttpRequest object inside and make calls automatically. But developer has to define certain attribute values to make call smoothly.

When the call executes successfully success function will be called and the appropriate action will be executed inside it. On error, error function will be called and the appropriate action will be executed. There is a complete attribute also and user can define a function on complete event. Please check JQuery docs for more information.

 

Running Web Application

Let’s run the Web application. Enter text in the textbox and click the ‘Click’ button.