Create WCF RESTFul Service

Introduction

We can use WCF to build Restful services in .NET.

RESTful Service

Representation State Transfer (REST) is an architecture style. It is a set of constraints based on the architectural style of the World Wide Web. Concepts to building RESTful services using Windows Communication Foundation (WCF). REST embraces the Web and HTTP. REST services are built to follow the specific constraints of the REST architectural style.

RESTful services model the interaction with user agents based on resources. Each resource is represented by a unique URI and the user agent uses the uniform interface of HTTP to interact with a resource via that URI. In REST, resources are identified by a unique URI. This is one of the constraints of architectural style. The following figure shows the four main verbs of the uniform interfaces GET, POST, PUT and DELETE.

RESTful

Implementing Simple RESTful Service Example

Create your first simple RESTful service that returns data in XML format. The following is the procedure for creating the RESTful service.

  1. Open Visual Studio.

  2. Select "File" -> "New" -> "Project...", select WCF from the left and create a new WCF Service Application. Name it “SimpleRESTfulService”.

     service applivation in wcf

  3. Now add a class to the project named Employee. We use this class to return the data. Add the following code to that class.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Runtime.Serialization;  
    5. using System.Web;  
    6.   
    7. namespace SimpleRESTfulService  
    8. {  
    9.     [DataContract]  
    10.     public class Employee  
    11.     {  
    12.         [DataMember]  
    13.         public int EmpID { getset; }  
    14.   
    15.         [DataMember]  
    16.         public string EmpName { getset; }  
    17.   
    18.         [DataMember]  
    19.         public string City { getset; }  
    20.   
    21.         [DataMember]  
    22.         public string EmpDesg { getset; }  
    23.     }  
    24. }  
  4. Add one method to the IService1 interface.

    GetEmpList() like the following.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Runtime.Serialization;  
    5. using System.ServiceModel;  
    6. using System.ServiceModel.Web;  
    7. using System.Text;  
    8.   
    9. namespace SimpleRESTfulService  
    10. {      
    11.     [ServiceContract]  
    12.     public interface IService1  
    13.     {  
    14.         [OperationContract]  
    15.         [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Xml,  
    16.                    BodyStyle = WebMessageBodyStyle.Bare,  
    17.                    UriTemplate = "GetEmpList/")]  
    18.         List<Employee> GetEmpList();  
    19.     }  
    20. }  
    Now understand the following methods WebInvoke attribute parameters:

    • Method = “GET”, represents an HTTP GET request.

    • ResponseFormat = WebMessageFormat.Xml, response format will be XML here but we can return JSON also.

    • BodyStyle = WebMessageBodyStyle.Wrapped, indicates both the request and response are wrapped.

    • UriTemplate = “GetEmpList/”, it has two parts, URL path and query.

  5. Now implement a RESTful service and add the GetEmpList() method to the Service1 class like the following.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Runtime.Serialization;  
    5. using System.ServiceModel;  
    6. using System.ServiceModel.Web;  
    7. using System.Text;  
    8.   
    9. namespace SimpleRESTfulService  
    10. {      
    11.     public class Service1 : IService1  
    12.    {  
    13.         //This is for temporary data to retrive  
    14.         List<Employee> lstEmployee = new List<Employee>()  
    15.         {  
    16.             new Employee{ EmpID = 1, EmpName = "Krishna", City ="Mathura", EmpDesg = "Project Manager"},  
    17.             new Employee{ EmpID = 2, EmpName = "Radha", City ="Mathura", EmpDesg = "Practice Manager"},  
    18.             new Employee{ EmpID = 3, EmpName = "Jeetendra", City ="Pune", EmpDesg = "Software Developer"},  
    19.             new Employee{ EmpID = 4, EmpName = "Anil", City ="Pune", EmpDesg = "Administrator"},  
    20.         };  
    21.   
    22.         /// <summary>  
    23.         /// GetEmpList  
    24.         /// </summary>  
    25.         /// <returns></returns>  
    26.         public List<Employee> GetEmpList()  
    27.         {  
    28.             try  
    29.             {  
    30.                 return lstEmployee;  
    31.             }  
    32.             catch (Exception)  
    33.             {                  
    34.                 throw;  
    35.             }  
    36.         }  
    37.     }  
    38. }  
  6. Configure the service and behaviors in the Web.config file like the following:
    1.  <?xml version="1.0"?>  
    2. <configuration>  
    3.   <appSettings>  
    4.     <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />  
    5.   </appSettings>  
    6.   <system.web>  
    7.     <compilation debug="true" targetFramework="4.5" />  
    8.     <httpRuntime targetFramework="4.5"/>  
    9.   </system.web>  
    10.   <system.serviceModel>  
    11.     <services>  
    12.         <service name="SimpleRESTfulService.Service1" behaviorConfiguration="serviceBehavior">  
    13.                 <endpoint address="" binding="webHttpBinding" contract="SimpleRESTfulService.IService1"                                  behaviorConfiguration="web"></endpoint>  
    14.           </service>  
    15.    </services>  
    16.     <behaviors>  
    17.       <serviceBehaviors>  
    18.         <behavior name="serviceBehavior">  
    19. <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>            
    20.           <serviceDebug includeExceptionDetailInFaults="false"/>  
    21.         </behavior>  
    22.       </serviceBehaviors>  
    23.     <endpointBehaviors>  
    24.               <behavior name="web">  
    25.                     <webHttp/>  
    26.                </behavior>  
    27.           </endpointBehaviors>  
    28.     </behaviors>  
    29.     <protocolMapping>  
    30.         <add binding="basicHttpsBinding" scheme="https" />  
    31.     </protocolMapping>      
    32.     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />  
    33.   </system.serviceModel>  
    34.   <system.webServer>  
    35.     <modules runAllManagedModulesForAllRequests="true"/>     
    36.     <directoryBrowse enabled="true"/>  
    37.   </system.webServer>  
    38. </configuration>  
    In this config file we added the Service and Behaviors, this webHttpBinding is the binding used for the RESTful service.

  7. Right-click on the Service1.svc.cs file and it will show like the following:

    Service

    Just modify the URL in the browser and add “GetEmpList/” to it. So, this is the UriTemplete we defined as the service contract method. It will show the record of employees in XML format.

    xml code

Summary

I hope you understand the concept of creating WCF RESTful services. If you have any suggestion regarding this article then please contact me.