WCF Services using REST

Posted: January 22, 2011 in WCF

WCF Using REST
REST stands for Representational State Transfer. Architectural pattern more inclined towards web. Web of Services should work in the same way as Web Of Pages works – Each resource is identified by an 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. 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 :
1. Identify each resource uniquely. Resource can be anything a Website, HTML page, xml document etc.
2. Simple and Open – It is an architecture pattern and can be applied to any system. Uses only standard Http Verbs.
3. Use Universal API – Http – It can be used by any client or can be called from any programming language. It is technology independent.
4. 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 :
1. LightWeight – uses POX or JSON or ATOMPub for data transmission
2. REST does not support WS-* standard.
3. 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.
4. Browsers can talk to rest services directly because REST works using URIs, QueryStrings, SSL.
5. WADL (Web Application Description Language) is a new standard available to support metadata for REST services.
6. Uses only standard Http Verbs and is technology independent.

Limitations :
1. Less secular has they do not obey WS-* specifications
2. No metadata – WSDL. WADL is available but still its not universally accepted.

WCF REST basics

1. Is supported since Dotnet 3.5. There are readily available templates for REST projects.Dotnet 3.5 has REST starter kit as well.
2. 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
3. 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.
4. WebGet and WebInvoke (all other verbs apart from GET) attributes were added to WCF. Message transmission format is POX or JSON.
5. UriTemplate :
o String that allows to define the structure of the URL. It is similar to ASP.Net Routing.
o UriTemplate only supports string parameters.
o 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.
o 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 :
URI Template
/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/*

6. Global.asax is used to set the route to your service using the new ServiceRoute class
7. 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 Soure 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 following fields

ID – Primary Key, varchar
Name – varchar
Code – varchar

This entity is available under SampleEntities Object context.

My code looks as seen below :

————————————————————————————————

using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfRestService1
{
// Start the service and browse to http://:/Service1/help to view the service’s generated help page
// NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
// a single instance of the service to process all calls.
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
// NOTE: If the service is renamed, remember to update the global.asax.cs file
public class AreaService
{

[WebGet(UriTemplate = “/GetAllAreas”, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
public List

GetAllAreas()
{
SampleEntities1 ctx = new SampleEntities1();

var allAreas = (from p in ctx.Areas select p).ToList

();
return allAreas;
}

[WebGet(UriTemplate = “/GetArea/{id}”, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public Area GetAreaWithID(string id)
{
SampleEntities1 ctx = new SampleEntities1();
var area = (from p in ctx.Areas where p.ID == id select p).Single();
return area;
}

[WebInvoke(UriTemplate = “/AddArea/{id} {name} {code}”,Method=”POST”)]
public void AddArea(string id, string name, string code)
{
SampleEntities1 ctx = new SampleEntities1();
Area a1 = new Area { ID = id, Name = name, Code = code };
ctx.Areas.AddObject(a1);
ctx.SaveChanges();
}

[WebInvoke(UriTemplate = “/Delete/{id}”, Method = “DELETE”, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void DeleteArea(string id)
{
SampleEntities1 ctx = new SampleEntities1();
Area a1 = ctx.Areas.Where(p => p.ID == id).SingleOrDefault();
ctx.Areas.DeleteObject(a1);
ctx.SaveChanges();
}

}
}

——————————————————————————————-

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 tranmission. 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 wont be any manual changes to the default web.config provided by the template . However, an entry for ADO.Net Entity object will be added that too once you configure the ADO.Net Entity.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s