Oct 26, 2012

RESTful Service

1. Uses HTTP as a communication protocol for remote interactions.

2. Rather than singular service endpoint, we have many individual resource/URIs. So its resource oriented architecture.

3. URIs (resources) supports multiple HTTP verbs (GET,PUT,POST,DELETE,HEAD,OPTION) and HTTP response codes.

GET, HEAD, and OPTIONS - Safe methods that aren't intended to have side effects
GET,PUT,DELETE,HEAD,OPTION - Idempotent,can be repeated multiple times without harm.
POST - Server define actual function, cannot be considered safe/idempotent by clients.

Refer to following specification for detail of HTTP Method RFC 2616 §9

HTTP defines a suite of standard response codes that specify the result of processing the request.
Successful 2xx
Redirection 3xx
Client Error 4xx
Server Error 5xx

The HTTP specification also defines a suite of headers that can be used to negotiate behavior between HTTP clients and servers. These headers provide built-in solutions for important communication concepts like redirection, content negotiation, security (authentication and authorization), caching, and compression.

Few Examples

GET http://<host>/ExploringMvc/api/Product?id=1 HTTP/1.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Cache-Control: private, max-age=60, s-maxage=0
Content-Length: 3495
Content-Type: text/html; charset=utf-8
Content-Type: application/json; charset=utf-8
Date: Mon, 29 Oct 2012 00:42:54 GMT
Expires: Thu, 01 Dec 1994 16:00:00 GMT
ETag: 792373472
Last-Modified: Mon, 29 Oct 2012 00:55:44 GMT
If-Match: "xyzzy"
If-Modified-Since: Mon, 31 Oct 2012 00:42:54 GMT

Refer to following specification for detail of HTTP Header RFC 2616 §14

Resource can support multiple media type which can be negotiated between client/server.

4. Response contains number of hypermedia controls for different things to do next. This allows the server to change its URI scheme without breaking clients. The reason it’s called the “Web” is because resources can contain hyperlinks  to other resources, thereby creating a Web of resources.

From RPC-style to RESTful
Unlike RPC-style, you no longer focus on designing methods. Instead, you focus on the resources that make up your system, their URIs, and their representations and then you decide which of HTTP Verb you’ll support for each resource. So you short of move from Verbs to Nouns. If I am designing RPC-style service my focus will be on following operations
GetProductList()
GetProduct(int id)
AddProduct(Product product)
DeleteProduct(int id)
UpdateProduct(Product product)

If you notice that all above operations is for Product resource. So moving from RPC-style to RESTful, my focus will shift to Product resource. And then I will decide which of HTTP Verbs I need to support.

In RPC, Contract is service description document. All of service endpoint,operation, data type argument return, exception are defined in self contained application protocol defination

In REST,

  • contract is uniform interface.Action/Error semantics are specified by uniform interface.
  • Input and output are tied to media type specification.
  • State transitions are specified by hype mdeia
  • no service/operation, only resources and standard control data element such as http verb
  • no data type, no argument, no return value, they are simply media type, which are sequence of bytes from view point of uniform interface.
  • in rest hyper media driven workflow enable relationship between client/server to be much more dynamic in the sense that component can be moved around like resources can be added without breaking client.
  • generating proxy is not simple as in case of REST
  • in a truly RESTful architecture, the concept of statelessness implies that all relevant application states must be supplied with each and every request.By relevant, it is meant that whatever is required by the REST API to process the request and serve an appropriate response.


Reference:
http://martinfowler.com/articles/richardsonMaturityModel.html
http://www.w3.org/Protocols/rfc2616/rfc2616.html

Oct 19, 2012

ASP.NET Web API Intoduction


ASP.NET Web API is framework built on top of ASP.NET, for building RESTful applications on .NET Platform. These are intended to return data in the form of JSON/XML etc  rather than HTML markup. This can be used to create HTTP services that only use the standard HTTP concepts (URIs and verbs), and to to create services that use more advanced HTTP features – request/response headers, hypermedia concepts etc.

Some Key features
. Support for MVC style URL routing
. Content Negotiation based on Accept headers (Content-Type: application/json or xml etc) for request and response serialization.
. Easily extensible Formatter, default is JSON.NET. Refer to http://json.codeplex.com/ for feature comparison
. MVC style convention-over-configuration
. Easily extensible similar to MVC
. Testable using testing concepts similar to MVC
. Parameter binding(using model binding and formatter)
. This framework borrows a lot of concepts from ASP.NET MVC.


With earlier version of Mvc there is an option of calling Controller.Json Method, which creates a JsonResult object that serializes the specified object to JSON format. Also there is an option of writting custome Xml Action result and similarly for any other format. But this doesn't provide a  way to automatically negotiate content types and serve various content formats directly.

Other option is WCF service with the use of webHttpBinding. In spite of complicated configuration, I like this framework specially for the reason this is designed for transport independent. This bring to an important point in choosing between WCF and ASP.NET Web API. If you need service which need to support multiple transport protocol, Wcf is a way to go, but if you are designing service only for HTTP, then Web API could be a better option as it has less complicated configuration, little simpler in terms of use of attributes (for specifying verb,Uri) and support for testing as this was an important goal throughout the design and development around ASP.NET MVC. Also WCF was primarily designed for SOAP-based XML messages. I ran into few problems in past around this as example I was having operation which was throwing FaultException (System.ServiceModel). This works great as long as I was using this for SOAP but when I started using the same service for end point with webHttpBinding, I was not getting desired behaviour. Later on I realised that for this to work nicely with webHttpBinding I need to throw WebFaultException(System.ServiceModel.Web). So I finally moved this error handling as a part of endpoint behaviour to make my serivce transport independent. Refer to my WCF blog on detail solution.

Using raw HTTP Handlers and Modules in the core ASP.NET runtime is also one option but you have to do pretty much every thing by hand.

Web API is similar to MVC but not the Same. Coming with mind set of ASP.NET Mvc I struggled a lot for following difference. I am still not sure why there is difference in behavior.
. You cannot have two action parameters to be bind from body. Similar to ASP.NET Mvc I was expecting this to work. Refer to my blog on parameter binding for detail on this.
. ActionFilter are designed differently. API uses System.Web.Http.Filters.ActionFilterAttribute where as MVC uses System.Web.Mvc.ActionFilterAttribute. This means if you implement an MVC ActionFilter and you want that same functionality in your Web API you'll end up creating the filter twice.

Oct 18, 2012

Web API-My First Look At Parameter Binding


This takes http request and convert it into .Net type which is passed as action parameter. Without this every action would have to take request message and manually extract parameter.

WebAPI uses model binding (same as MVC ValueProviders) to read from the query string and Formatters to read from the body. Formatters gets the list of formatters from the HttpConfiguration, and then uses the request’s content-type to select an appropriate formatter. WebAPI has some default formatters-JSON.Net.

Following code show few configuration which can be done around JsonFormatter
//config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true; //Use this for DataContractJsonSerializer
config.Formatters.JsonFormatter.Indent = true;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();

If the parameter has no attribute on it, then the decision is made purely on the parameter’s .NET type. Simple types uses model binding. Complex types uses the formatters.

By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once. This means if formatter uses this for binding model, then you cannot access request content (Request.Content) inside action. This also means you cannot have two action parameters to be binded from body. Something like this will throw exception as "Can't bind multiple parameters ('body' and 'body1') to the request's content.",

public HttpResponseMessage PostProduct([FromBody] string body, [FromBody] string body1)

This behavior is different than Mcv, in which case model binding can repeatedly search through value providers.


Oct 15, 2012

Form Authentication(FormsAuthenticationModule)


Forms authentication cookie contains forms authentication ticket which is passed with each request. In case of cookieless forms authentication, the ticket will be passed in the URL in an encrypted format.

The ticket is encrypted and signed using the <machineKey> configuration element of the server's Machine.config file. If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively.

The authentication ticket contains various bits of information, such as the user name, the issue and expiry dates and user data.

Forms authentication tickets can be generated manually by using the FormsAuthenticationTicket class.

FormsAuthentication cookie name is .ASPXAUTH which is by default set and send to the browser once user is authenticated.

.ASPXAUTH=095F6C2AF0126AF84BD5A30AD2866328E06F61755EA6FCDEDAA5A79F9039FB38AC4812628A42C700B7E927B58CA6B50F831DA2143A06385AA422ED313CB39303C3C0DA75DCFE9BCF363B7969FCFC6B0114D362CE6C1A04C424C7B1D46A440170B1DABD47E6DD8C91D6EE64B74F5224B6


In case of non-persistent cookie, if the ticket is expired, cookie will also expire, and the user will be redirected to the logon page. If the ticket is marked as persistent, where the cookie is stored on the client box, browsers can use the same authentication cookie to log on to the Web site any time. FormsAuthentication.SignOut removes the forms-authentication ticket information from the cookie or the URL if CookiesSupported is false.