Introduction
This article explains the WCF REST based services in details.
Description
There are mainly 2 types of services available in WCF.
- SOAP Based services.
- 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.
- GET: Requests a specific representation of a resource.
- PUT: Create or update a resource with the supplied representation.
- DELETE: Deletes the specified resource.
- 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.
- Interoperability
- Scalability
- Performance
- Efficiency
- Stateless
- Supports caching of URI of the service.
- Independent Evolution.
- 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.
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.
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.
- <DocumentElement>
- <Students>
- <StudentID>1</StudentID>
- <StudentName>Sankalp</StudentName>
- <categoryID>1</categoryID>
- <AverageMark>99</AverageMark>
- <CategoryName>IT</CategoryName>
- </Students>
- <Students>
- <StudentID>2</StudentID>
- <StudentName>Syam</StudentName>
- <categoryID>2</categoryID>
- <AverageMark>98</AverageMark>
- <CategoryName>CSE</CategoryName>
- </Students>
- <Students>
- <StudentID>3</StudentID>
- <StudentName>Sambit</StudentName>
- <categoryID>3</categoryID>
- <AverageMark>97</AverageMark>
- <CategoryName>ECE</CategoryName>
- </Students>
- </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.
- [ServiceContract]
- public interface IStudentService
- {
- [OperationContract]
- [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Json,
- BodyStyle = WebMessageBodyStyle.Bare,
- UriTemplate = "GetStudentName/{studentId}")]
- string GetStudentName(string studentId);
-
- [OperationContract]
- [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
- BodyStyle = WebMessageBodyStyle.Bare,
- UriTemplate = "GetStudentMark/{studentId}")]
- string GetStudentMark(string studentId);
-
- [OperationContract]
- [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
- BodyStyle = WebMessageBodyStyle.Bare,
- UriTemplate = "GetStudentCount")]
- string GetStudentCount();
-
- }
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.
-
-
-
-
-
- public string GetStudentName(string studentId)
- {
- string studentName = string.Empty;
-
- try
- {
- XDocument doc = XDocument.Load("D:\\StudentData.xml");
-
- studentName =
- (from result in doc.Descendants("DocumentElement")
- .Descendants("Students")
- where result.Element("StudentID").Value
- == studentId.ToString()
- select result.Element("StudentName").Value)
- .FirstOrDefault<string>();
-
- }
- catch (Exception ex)
- {
- throw new FaultException<string>
- (ex.Message);
- }
- return studentName;
- }
-
-
-
-
-
-
- public string GetStudentMark(string studentId)
- {
- string strProductQty = string.Empty;
-
- try
- {
- XDocument doc = XDocument.Load("D:\\StudentData.xml");
-
- strProductQty =
- (from result in doc.Descendants("DocumentElement")
- .Descendants("Students")
- where result.Element("StudentID").Value
- == studentId.ToString()
- select result.Element("AverageMark").Value)
- .FirstOrDefault<string>();
- }
- catch (Exception ex)
- {
- throw new FaultException<string>
- (ex.Message);
- }
- return strProductQty;
- }
-
-
-
-
-
- public string GetStudentCount()
- {
- try
- {
- XDocument doc = XDocument.Load("D:\\StudentData.xml");
- return doc.Descendants("Students").Count().ToString();
- }
- catch (Exception ex)
- {
- throw new FaultException<string>
- (ex.Message);
- }
-
- }
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.
- <system.serviceModel>
- <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
- multipleSiteBindingsEnabled="true" />
- <services>
- <service name="RESTDemo.StudentService">
- <endpoint address="" behaviorConfiguration="RESTDemo.StudentServiceAspNetAjaxBehavior"
- binding="webHttpBinding" contract="RESTDemo.IStudentService" />
- </service>
- </services>
- <behaviors>
- <endpointBehaviors>
- <behavior name="RESTDemo.StudentServiceAspNetAjaxBehavior">
- <webHttp/>
- </behavior>
- </endpointBehaviors>
- </behaviors>
- </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 ArchitectureI hope it will help you.