WCF Rest Service

REST stands for Representational State Transfer. It is an Architectural pattern more inclined towards a web. Web of Services should work in the same way as Web Of Pages works - each resource is identified by a unique id in the form of an URI. Resource can be anything; a Website, HTML page, XML document, etc. Services can be built on top of REST architecture. It is a structured way of uniquely identifying resources and accessing them. Uses only standard verbs POST, GET, PUT and DELETE. REST is not a standard as such but just an architectural pattern.
 

Rest Principles

  • Identify each resource uniquely. Resource can be anything; a website, HTML page, xml document etc.
  • Simple and Open - It is an architecture pattern and can be applied to any system. Uses only standard Http Verbs.
  • Use Universal API - Http - It can be used by any client or can be called from any programming language. It is technology independent.
  • Linked Resources - resources can contain link to other resources.
Rest usage examples
 
REST - Yahoo web services use REST, including Flickr, del.icio.us API uses it
SOAP and REST both - EBay and Amazon
Google Web Services - SOAP
 
High REST and Low REST
 
High REST - Uses all 4 verbs and uses well-constructed URIs.
LOW REST - Uses mostly Get and POST verbs only. More suited for Ajax services.
 
NOTE
 
PUT and DELETE verbs are not supported by all browsers. Also, PUT and DELETE can be handled using POST verb itself.
 

HTTP Verbs

 
HTTP defines nine methods (sometimes referred to as "verbs") indicating the desired action to be performed on the identified resource.
 
Verb Action
GET Fetch a resource
PUT Update resource
DELETE Delete a resource
POST Append to resource
 

Advantages of REST

  • LightWeight - uses POX or JSON or ATOMPub for data transmission
  • REST does not support WS-* standard.
  • Message transmission can be controlled and supports different formats such as JSON, POX, AtomPub. Developers need not understand SOAP message structure as in case of SOAP.
  • Browsers can talk to rest services directly because REST works using URIs, QueryStrings, SSL.
  • WADL (Web Application Description Language) is a new standard available to support metadata for REST services.
  • Uses only standard Http Verbs and is technology independent.

Limitations of REST

  • Less secular has they do not obey WS-* specifications.
  • No metadata - WSDL. WADL is available but still its not universally accepted.

WCF REST basics

  • Is supported since .Net 3.5. There are readily available templates for REST projects. The .Net 3.5 has REST starter kit as well.
  • REST in .NET 4 is greatly simplified and leverages the Web Routing capabilities used in ASP.Net MVC and other parts of the web frameworks
  • Special binding available for REST support

    WebHttpBinding - A binding used to configure endpoints for Web services that are exposed through HTTP requests instead of SOAP messages.
  • WebGet and WebInvoke (all other verbs apart from GET) attributes were added to WCF. Message transmission format is POX or JSON.
  • UriTemplate
    • String that allows to define the structure of the URL. It is similar to ASP.Net Routing. 
    • UriTemplate only supports string parameters.
    • The segments in curly braces describe variables or holes. The segments not in curly braces describe literal strings. Template is bound with parameters to fill the holes.
    • UriTemplate can have a single wildcard character and also default values for variables. UriTemplate also includes wildcard capabilities. UriTemplate="*" will route all URIs to one method

      Example
      /weather/wa/seattle/cycling /weather/{state}/{city}/{activity}
      /weather/wa seattle /weather/{state}{city}
      /weather/USA/wa/Climate /weather/{country=USA}/{state}/Climate
      /weather/A /weather/B /weather/*
       
  • Global.asax is used to set the route to your service using the new ServiceRoute class
  • SOAP and REST based endpoints can co-exist side by side.
http://www.servicestack.net/ framework does it for you can you can as well do it yourself by defining multiple endpoints.
 
Sample Source Code
 
I am assuming that you have added an ADO.Net Entity Model object in your project file which maps to an Area table having the following fields
 
ID - Primary Key, varchar
Name - varchar
Code - varchar
 
This entity is available under SampleEntities Object context.
 
My code looks as below:

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.ServiceModel;  
  4. using System.ServiceModel.Activation;  
  5. using System.ServiceModel.Web;  
  6. namespace WcfRestService1 {  
  7.  // Start the service and browse to http://:/Service1/help to view the service's generated help page  
  8.  // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want  
  9.  // a single instance of the service to process all calls.   
  10.  [ServiceContract]  
  11.  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
  12.  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]  
  13.  // NOTE: If the service is renamed, remember to update the global.asax.cs file  
  14.  public class AreaService {  
  15.   
  16.   [WebGet(UriTemplate = "/GetAllAreas", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]  
  17.   public List < area > GetAllAreas() {  
  18.    SampleEntities1 ctx = new SampleEntities1();  
  19.   
  20.    var allAreas = (from p in ctx.Areas select p).ToList < area > ();  
  21.    return allAreas;  
  22.   }  
  23.   
  24.   [WebGet(UriTemplate = "/GetArea/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]  
  25.   public Area GetAreaWithID(string id) {  
  26.    SampleEntities1 ctx = new SampleEntities1();  
  27.    var area = (from p in ctx.Areas where p.ID == id select p).Single();  
  28.    return area;  
  29.   }  
  30.   
  31.   [WebInvoke(UriTemplate = "/AddArea/{id} {name} {code}", Method = "POST")]  
  32.   public void AddArea(string id, string name, string code) {  
  33.    SampleEntities1 ctx = new SampleEntities1();  
  34.    Area a1 = new Area {  
  35.     ID = id, Name = name, Code = code  
  36.    };  
  37.    ctx.Areas.AddObject(a1);  
  38.    ctx.SaveChanges();  
  39.   }  
  40.   
  41.   [WebInvoke(UriTemplate = "/Delete/{id}", Method = "DELETE", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]  
  42.   public void DeleteArea(string id) {  
  43.    SampleEntities1 ctx = new SampleEntities1();  
  44.    Area a1 = ctx.Areas.Where(p = & gt; p.ID == id).SingleOrDefault();  
  45.    ctx.Areas.DeleteObject(a1);  
  46.    ctx.SaveChanges();  
  47.   }  
  48.   
  49.  }  
  50. }  
I am using the default web.config which uses standard endpoints. WebHttpBinding is used for REST services as it does not Soap message format for data transmission. You can customize the message transmission format and choose either POX, JSON, AtomPub to name a few.
 
I am using C# Rest WCF Template available for .Net 4.0. It uses Routing and WebHttpBinding internally. So, there won't be any manual changes to the default web.config provided by the template. However, an entry for ADO.Net Entity object will be added too once you configure the ADO.Net Entity.


Similar Articles