Pages

Thursday, March 14, 2013

Part 1 - Create RESTful WCF Service

This is the first part about building Windows Communication Foundation (WCF) services using the architectural style known as Representational State Transfer (REST). You may know that this got famous from the time of its existing around 2000.

Let me start with basic understanding and then the implementation of RESTFul WCF Service.

Brief:-


WCF service will use SOAP, but if you build a REST service, clients will be accessing your service with a different architectural style (calls, serialization like JSON, etc.). REST uses some common HTTP methods to insert/delete/update/retrieve information which is below:
  1. GET - Requests a specific representation of a resource
  2. PUT - Creates or updates a resource with the supplied representation
  3. DELETE - Deletes the specified resource
  4. POST - Submits data to be processed by the identified resource

Implementation:-
In my first implementation, let me explain the GET method.
  • Open your Visual Studio 2012, Go to New Project as below. Give the Name and Location and Click Ok.


  • You will get default solution structure in the Solution Explorer.

  • You can Rename or can use the sample .svc files. In my case I am just renaming the files to easy readable format. as Service1svc to ExampleService.svc and interface IService1.cs to IExampleService.cs
namespace SampleRestFulWCFService
{
    [ServiceContract]
    public interface IExampleService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
          UriTemplate = "GetData/{id}",
          ResponseFormat = WebMessageFormat.Json,
          BodyStyle = WebMessageBodyStyle.Wrapped)]
        string GetData(string value);
    }
}

  • Now open the ExampleService.svc.cs file and create a method with name GetData as below
public string GetData(string value)
{
return "You entered the Value:"+value;
}

  • Build and browse the Application.
  • By default it opens the URL containing the ExampleService.svc for eg:- http://localhost/SampleRestFulWCFService/ExampleService.svc
  • Add the following string in the URL as "/GetData/Sample" which means http://localhost/SampleRestFulWCFService/ExampleService.svc/GetData/Sample
Now you will see as "You entered the Value: Sample" This is a JSON Object. 

MVC Application - Not able to browse

Sometime when you are browsing the MVC Application through your IIS Server, you may facing an issue of not able to browse. You may see the Directory list rather than Home Page. In that case, please add below line in your web.config file under the System.WebServer tag.

 <modules runAllManagedModulesForAllRequests="true"></modules>

Now once restart the Website in your IIS and browse your MVC Application. Hope you can enjoy now.

Please post if any issues still arises.