Wednesday, August 6, 2014

What, Why REST?



·         Why REST?

·         What is REST?

·         WCF and REST




Two reasons – One is soft and the other is hard( likely imposed).


1.       First, REST offers some significant features and benefits over RPC technologies in many cases.

2.    Second, Microsoft is moving many of its own implementations away from RPC technologies (such as SOAP) and goings toward REST. This means that even if you are not convinced or motivated to use REST to build your own systems, you'll need to know how to interact with other MS Frameworks & Technologies as they have already moved to REST,


What is REST?


REST is an architectural style - Used to build software in which clients (User Agents) can make requests of services (Endpoints).

REST means that each unique URL is a representation of some object (Resource).





Other Verbs

"/ "


Retun All Years Subscriptions




A particular year's issues




A particular issue




An article



E.g. http://localhost/Issues.svc/  and http://localhost/Issues.svc/2007




To add an article to December 2008, the client would POST an article resource to http://localhost/Issues.svc/2008/December and a new article would be added to that issue.


To suuport this -  WCF ServiceContract Definition would look like below.




public interface IMSDNMagazineService




    IssuesCollection GetAllIssues();



    [WebGet(UriTemplate = "/{year}")]

    IssuesData GetIssuesByYear(string year);



    [WebGet(UriTemplate = "/{year}/{issue}")]

    Articles GetIssue(string year, string issue);



    [WebGet(UriTemplate = "/{year}/{issue}/{article}")]

    Article GetArticle(string year, string issue, string article);



    [WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]

    Article AddArticle(string year, string issue, Article article);






WCF is more geared toward RPC (using SOAP). Till Framework 3.0 WCF had the ability to expose and consume REST services as part of the .NET. However what it lacked was a programming model needed to make using REST with WCF easy.


This is been mitigated in Framework 3.5 - Both a Programming Model and those pieces of Infrastructure were added to existing System.ServiceModel.Web assembly.


The Programming Model additons were –


o    WebGetAttribute and WebInvokeAttribute, and

o    URI Template Mechanism - Enables to declare the URI and Verb to which each method. (As show above).


The Infrastructure additons were –


o    Behavior Infrastructure

o    Binding (WebHttpBinding) and

o    Behavior (WebHttp­Behavior) - Provide the correct networking stack for using REST


o    Hosting Infrastructure additons were –

o    Custom Service­Host (WebServiceHost) and

o    ServiceHostFactory (WebServiceHostFactory)


WebGetAttribute and WebInvokeAttribute


WCF builds connected systems, is by routing messages to methods, defined in your service class.




o    By default, WCF does the routing (also known as Dispatching) based on the concept of action.

o    This system of routing is tightly coupled to SOAP since the SOAP specification's Action header is used by default.

o    The value of Action is based on (method name + the namespace of your service) Or via a custom value (set via the OperationContractAttribute.Action property).

o    For this dispatching to work, an action needs to be present in every message that WCF receives on your behalf.

o    Each unique action is mapped to a particular Action method.




o    In this case, the default dispatcher is replaced by one that routes based not on Action, but instead based on the (URI  + HTTP verb being used) in the  request.

o    This routing (done by a class called WebHttpDispatchOperationSelector) enables you to easily implement a RESTful endpoint.

o    This dispatcher is configured on each endpoint by a behavior named WebHttpBehavior, which must be added to each endpoint. (TBD)

o    The key to making this work is for the WebHttpDispatch­OperationSelector to know How To Map Different Uris And Verbs To Your Methods.

o    For this, the WebGetAttribute and WebInvokeAttribute must be added to the methods on your WCF ServiceContract type.


WebGetAttribute tells the dispatcher that the method should respond to HTTP GET requests.

WebInvokeAttribute is mapped to HTTP POST by defaul.

Also the WebInvokeAttribute.Method property can be set to support any of the other HTTP verbs (PUT and DELETE being the two most common).


UriTemplate and UriTemplateTable


In Non-RESt, By default, the URI is determined by the name of the method (added onto the base URI of the endpoint).

In RESTful, what you want to expose as URIs are nouns.

For this reason, WCF + REST,  requires customization of URIs for each method  - This is achvieved by using templates.

Such Templates are set via the UriTemplate property on WebGetAttribute or WebInvokeAttribute.


UriTemplate - Enables customization of the URI for each Method And Verb combination, by using a special template syntax (as shown above).


WebHttpBinding and WebHttpBehavior


WebHttpBinding – Used for a RESTful endpoint. Unlike others this is fairly simple.

It contains only two components: the HTTP transport and the Text Message Encoder (set to not expect or use SOAP, just plain XML).


WebHttpBehavior - Is the object that causes the “URI + HTTP Verb” dispatcher to be used.


Note: Below Code for self-hosting a WCF RESTful endpoint.


·         WebHttpBinding and the WebHttpBehavior are almost always used together

·         You have to specify the WebHttpBinding when adding the endpoint to the ServiceHost.

·         Also you have to explicitly add the WebHttpBehavior to the endpoint to make the URI-plus-verb dispatching system work.



ServiceHost sh =  new ServiceHost(typeof(MSDNMagazineServiceType));

string baseUri = "http://localhost/MagazineService";

ServiceEndpoint se =   sh.AddServiceEndpoint(typeof(IMSDNMagazineService), new WebHttpBinding(), baseUri);

se.Behaviors.Add(new WebHttpBehavior());








      <service name="MSDNMagazine.MSDNMagazineServiceType">










        <behavior name="webby">








Note: Use either code or config.




WebServiceHost and WebServiceHostFactory


WCF is complex, in terms of configuration. To alleviate this concern with RESTful endpoints,, Microsoft added two new types to the .NET Framework 3.5


·         WebServiceHost and

·         WebServiceHostFactory




·         Is a ServiceHost-derived type, which simplifies self-hosting scenarios of RESTful endpoints.

·         The code to self-host with WebServiceHost looks like this



string baseUri = "http://localhost/MagazineService";

WebServiceHost sh =   new WebServiceHost(typeof(MSDNMagazineServiceType), new Uri(baseUri));





In the managed hosting scenario with WCF, inside IIS, WCF normally requires an .svc file that points to the service type, plus entries in the web.config file to inform WCF about the endpoint (the binding and behaviors among other configuration). To simplify the managed hosting scenario, Microsoft added WebServiceHostFactory.


·         Uses an open WCF extensibility point (using a custom ServiceHostFactory type) in the managed hosting scenario.

·         This enables a configuration-free experience for many RESTful services. The .svc file looks like this



<%@ ServiceHost


                        Service="MSDNMagazine.MSDNMagazineServiceType" %>




·         WebServiceHostFactory creates an instance of the WebServiceHost, and since the WebServiceHost will auto-configure the endpoint using WebHttpBinding and WebHttpBehavior. This no need for any configuration for this endpoint in the web.config at all.



Why Should You Care about REST?


Whether you have used proprietary either of the below two, these are the implementations of the client-server style we've had on the Microsoft platform.

·         RPC systems such as DCOM or .NET Remoting, or

·         Interoperable RPC technologies such as SOAP using ASMX(Web Service) or WCF,


So why learn or use REST?


·         The two main reason are as mentioned above.


The following is a list of other advantages (but don't consider this list exhaustive):





When RESTful endpoints are asked for data using HTTP, the HTTP verb used is GET.

Resources returned in response to a GET request can be cached in many different ways.


Conditional GET, which is a way that a client can check with the service if his version of the data is still the current version, is an optional implementation detail a RESTful endpoint can implement that can further improve speed and scalability.



REST encourages each resource to contain all of the states necessary to process a particular request.

RESTful services are much easier to scale out when they fulfill this constraint and can be stateless.



Many people advertize SOAP as being the most interoperable way to implement client-server programs.

But some languages and environments still don't have SOAP toolkits.

And some that do have toolkits are based on older standards that can't always communicate with toolkits that implement newer standards.


REST only requires an HTTP library to be available for most operations, and it is Certainly More Interoperable Than Any RPC Technology (including SOAP).



Here, the simplicity of using REST relates to URIs representing resources and the uniform interface.


Using the uniform interface simplifies development by freeing me from having to build an interface, contract, or API for each service I need to build. The interface (how clients will interact with my service) is set by the constraints of the architecture.



REST is Lightweight than SOAP because it does not requires lot of xml markup like SOAP.



This is not an exhaustive list nor should you take it as conclusive evidence that REST is the one and only true technology to use always.

You should be aware of the advantages so you can leverage them when appropriate


REST Vs SOAP - Which is the best approach?


Software Architects have been involving a never-ending debate about whether SOAP-based or REST-style web services are the right approach.

Yahoo's web services are using REST and Google using SOAP for their web services. Some organizations have web services for both REST and SOAP.


REST is Lightweight than SOAP because it does not requires lot of xml markup like SOAP.

I believe that SOAP will be the primary choice for Intranet & Enterprise Level Applications because SOAP and the WS-* specifications addresses many challenges of enterprise level applications such as Reliability, Distributed Transactions, and other WS-* services.

On the other hand, Internet applications will gear towards to REST because of REST’s explicitly Web-based approach and its simplicity.



RESTful services for WCF 3.5


WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

By adding the WebGet Attribute, we can define a service as REST based service that can be accessible using HTTP GET operation.

The below code shows how to expose a RESTful service

SOAP Based – WCF 3.0

REST Based – WCF 3.5


interface IStock
int GetStock(string StockId);

interface IStock
int GetStock(string StockId);



Arun Manglick


No comments:

Post a Comment