Understanding WCF REST Fundamentals

Introduction

This article explains the WCF REST based services in details.

Description

There are mainly 2 types of services available in WCF.

  1. SOAP Based services.
  2. REST Based services.
REST Overviews

In 2000 Roy Thomas Fielding introduced Representational State Transfer. It is referred to as REST as its acronym. REST emphasizes nouns or resources. This style dictates to think in terms of resources and their representation instead of just thinking about methods within a system. Using REST we can build scalable services using a uniform interface. REST defines transport-specific (HTTP) models focused on resources. REST does not tie with HTTP but in reality HTTP is the only protocol for building Restful services. REST builds on a uniform interface and common data formats. If we use HTTP to implement Restful services then a uniform interface is defined by various HTTP methods like GET, POST, PUT and DELETE and so on.
  1. GET: Requests a specific representation of a resource.

  2. PUT: Create or update a resource with the supplied representation.

  3. DELETE: Deletes the specified resource.

  4. POST: Submits data to be processed by the identified resource.

Those are the operations that can be invoked on the resources. When we get a resource then we are retrieving the representations of that resources over the protocol .We can represent the wide variety of data formats to represent the resources like HTML, XML and JSON and so on. But in the end we always use a uniform interface to interact with those resources that are exposed by our services.

Resource-Oriented Architecture

REST uses a Resource-Oriented architecture. Every resource is given an unique identifier, also known as a universal resource identifier (URI). The most common type of URI used on the Web today is a uniform resource locator (URL). Since a given URI uniquely identifies a resource, it can be saved for future use and shared with others. As long as you have the URI, you can enter it into a Web browser and retrieve the resource at some future point in time. Resources can contain hyperlinks to other resources, thereby creating a Web of resources. Hyperlinks make it possible to navigate from one resource to another using the target resource URI. When you retrieve a resource using a Web browser, you're really retrieving a representation of that resource. This implies that there could be multiple representations of a specific resource. There are many standard and common formats used on the Web today to represent resources that virtually all browsers understand.

Advantages

We have a standard uniform interface that can apply equally to all our resources that we expose through our service.

  1. Interoperability
  2. Scalability
  3. Performance
  4. Efficiency
  5. Stateless
  6. Supports caching of URI of the service.
  7. Independent Evolution.
  8. Through REST one can take most of the advantages of web infrastructures.

The Importance of GET

It is the most commonly used HTTP verb. Most of the web traffics use a GET request. GET simply means retrieve the representation of the resources. REST naturally embraces the importance of GET. It should not cause any side effect.

Designing Restful Services

  • Identify the resources the service will expose.
  • Enable HTTP bindings.
  • Expose methods via common interfaces.
  • Define your representation.

Demo of REST

Step 1

Open Visual Studio 2012 then selelct "File" -> "New" -> "Project...". We will then get the following Image. From the template choose Visual C# then choose WCF. Then select the WCF Service Application. Let's give the project the name RESTDemo, then click the OK button to go to the next step.

WCF service application

This gives us a basic WCF application template.

After creating the application from the Solution Explorer, we can remove the default files IService.cs and Service.svc.

wcf service

Step 2

Right-click on the project and click on the add new item. We will get the following image. Then choose Web then choose WCF Service. Then give the name to your service. I gave StudentService.svc. Then click the add button.

Step 3

Create a new XML file with the name StudentData.xml and save it in the D: drive. This XML file will act as the WCF service database. Look into the following XML file data.

  1. <DocumentElement>  
  2.           <Students>  
  3.               <StudentID>1</StudentID>   
  4.               <StudentName>Sankalp</StudentName>   
  5.               <categoryID>1</categoryID>   
  6.               <AverageMark>99</AverageMark>   
  7.               <CategoryName>IT</CategoryName>   
  8.            </Students>  
  9.           <Students>  
  10.               <StudentID>2</StudentID>   
  11.               <StudentName>Syam</StudentName>   
  12.               <categoryID>2</categoryID>   
  13.               <AverageMark>98</AverageMark>   
  14.               <CategoryName>CSE</CategoryName>   
  15.            </Students>  
  16.           <Students>  
  17.               <StudentID>3</StudentID>   
  18.               <StudentName>Sambit</StudentName>   
  19.               <categoryID>3</categoryID>   
  20.               <AverageMark>97</AverageMark>   
  21.               <CategoryName>ECE</CategoryName>   
  22.            </Students>         
  23.       </DocumentElement>  
Step 4

Add the ServiceContract and the OperationContracts to the IstudentService class to define the representations. Look into the code in the IstudentService class.
  1.    [ServiceContract]  
  2. public interface IStudentService  
  3. {         
  4.         [OperationContract]  
  5.         [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Json,  
  6.                                BodyStyle = WebMessageBodyStyle.Bare,  
  7.                                UriTemplate = "GetStudentName/{studentId}")]  
  8.         string GetStudentName(string studentId);  
  9.   
  10.         [OperationContract]  
  11.         [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,  
  12.                               BodyStyle = WebMessageBodyStyle.Bare,  
  13.                               UriTemplate = "GetStudentMark/{studentId}")]  
  14.         string GetStudentMark(string studentId);  
  15.   
  16.         [OperationContract]  
  17.         [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,  
  18.                               BodyStyle = WebMessageBodyStyle.Bare,  
  19.                               UriTemplate = "GetStudentCount")]  
  20.         string GetStudentCount();  
  21.     
  22. }  

Since I am getting the data from the XML file, I have used the webGet functions. The UriTemplate contains the function names and the parameters that the functions needed. Any request with this specific Uri type will be served the respective operation contract.

Step 5

Define the preceding functions in the StudentService.srv class. Add the following code in the specified class.
  1. /// </summary>
  2. /// This function will fetch the student name of the particular student id.  
  3. /// </summary>  
  4. /// <param name="studentId"></param>  
  5. /// <returns></returns>  
  6. public string GetStudentName(string studentId)  
  7. {  
  8.     string studentName = string.Empty;  
  9.   
  10.     try  
  11.     {  
  12.         XDocument doc = XDocument.Load("D:\\StudentData.xml");  
  13.   
  14.         studentName =  
  15.             (from result in doc.Descendants("DocumentElement")  
  16.             .Descendants("Students")  
  17.              where result.Element("StudentID").Value  
  18.                          == studentId.ToString()  
  19.              select result.Element("StudentName").Value)  
  20.             .FirstOrDefault<string>();  
  21.   
  22.     }  
  23.     catch (Exception ex)  
  24.     {  
  25.         throw new FaultException<string>  
  26.                 (ex.Message);  
  27.     }  
  28.     return studentName;  
  29. }  
  30.   
  31. /// <summary>  
  32. /// This function fetch the student mark from the xml file using student id.  
  33. /// </summary>  
  34. /// <param name="studentId"></param>  
  35. /// <returns></returns>  
  36. public string GetStudentMark(string studentId)  
  37. {  
  38.     string strProductQty = string.Empty;  
  39.   
  40.     try  
  41.     {  
  42.         XDocument doc = XDocument.Load("D:\\StudentData.xml");  
  43.   
  44.         strProductQty =  
  45.             (from result in doc.Descendants("DocumentElement")  
  46.             .Descendants("Students")  
  47.              where result.Element("StudentID").Value  
  48.                      == studentId.ToString()  
  49.              select result.Element("AverageMark").Value)  
  50.             .FirstOrDefault<string>();  
  51.     }  
  52.     catch (Exception ex)  
  53.     {  
  54.         throw new FaultException<string>  
  55.             (ex.Message);  
  56.     }  
  57.     return strProductQty;  
  58. }  
  59.   
  60. /// <summary>  
  61. /// This function counts the number of students present in the database.  
  62. /// </summary>  
  63. /// <returns></returns>  
  64. public string GetStudentCount()  
  65. {  
  66.     try  
  67.     {  
  68.         XDocument doc = XDocument.Load("D:\\StudentData.xml");  
  69.         return doc.Descendants("Students").Count().ToString();  
  70.     }  
  71.     catch (Exception ex)  
  72.     {  
  73.         throw new FaultException<string>  
  74.             (ex.Message);  
  75.     }             
  76.       
  77. }  
Step 6

The final task is to enable the service access through the browser or RESTfulness . We can do this in the web.config file.
  1. <system.serviceModel>  
  2.    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"  
  3.      multipleSiteBindingsEnabled="true" />  
  4.    <services>   
  5.      <service name="RESTDemo.StudentService">  
  6.        <endpoint address="" behaviorConfiguration="RESTDemo.StudentServiceAspNetAjaxBehavior"  
  7.          binding="webHttpBinding" contract="RESTDemo.IStudentService" />  
  8.      </service>  
  9.    </services>  
  10.    <behaviors>  
  11.      <endpointBehaviors>  
  12.        <behavior name="RESTDemo.StudentServiceAspNetAjaxBehavior">  
  13.          <webHttp/>  
  14.        </behavior>  
  15.      </endpointBehaviors>       
  16.    </behaviors>  
  17.  </system.serviceModel>  
Step 7

View the service file in the Solution Explorer by right-clickiing on the StudentService.srv file and view it in the browser.

Or you can click on the debug button, once the page is open choose the StudentService.srv file. You will get the following URL.

http://localhost:49712/StudentService.svc

In that URL pass the function name and its corresponding input parameters. Like in my code I got the following puts.

http://localhost:49712/StudentService.svc/GetStudentMark/3

o/p-> “97”

http://localhost:49712/StudentService.svc/GetStudentName/1

0/p-> "Sankalp"

http://localhost:49712/StudentService.svc/GetStudentCount

0/p-> “3”

Reference: Resource-Oriented Architecture

I hope it will help you. 


Similar Articles