A simple use case with OData Web Api

Scenario :

Assume a case where we have an Employee object and we have an nullable  integer named Age (int? Age).  There are two cases we want to achieve,the first case is to not update the Age property and we could achieve this by passing null value to Age and ignoring the Age Property while saving and second case is to reset the Age i.e Accept whatever is passed by Age Property and save it in db.

Solution :

We want to only update properties of Employee object that is being passed to the controller and we call it as “partial update”(PATCH).  In this case we update only what is being passed and leave the system unchanged. Microsoft provides OData for partial update.

  1. Get Microsoft ASP.NET Web API OData package from Nuget.
  2. In your controller  HTTP verb Method,you could make use of Delta<T>  to map your Employee object and this will take care of partial update with Patch Method provided by ODATA .

public ApiResponse<Statuscode> Patch(Delta<Employee>; employee)

{

var employeebyId == dbcontext.FirstorDefault(x=>x.EmpId ==employee.EmpId);

if(employee !=null)

{

employee.Patch(employeebyId ); // Partial update by ODATA

}

}

 

 

 

Enabling Web Api Tracing

By default ,Tracing is disabled in web api , tracing incoming request might help to track issues in production environment.

Enabling Tracing :

Install the following package from Nuget :

Microsoft.AspNet.WebApi.Tracing

and have the startup .cs configured as below

config.EnableSystemDiagnosticsTracing();

Trace/Log of incoming request to a controller

Capture

#Content Type vs Accept in Request Header

Accept : Tells the server  what the media type client needs as response.

“Accept”: text/html —Client expects the response as text/html.

Content-Type : Tells the server what media type the client sends when making a request.This is useful for server so that it can parse the request accordingly.

“Content-Type” :application/json –Client tells the server that it sending input as json.

 

#Content Negotiation in Web API?

A client might send a request with multiple media types in header

<pre class="prettyprint prettyprinted"><span class="pln">GET http</span><span class="pun">:</span><span class="com">//localhost.:21069/api/products/1 HTTP/1.1</span>
<span class="typ">Host</span><span class="pun">:</span><span class="pln"> localhost</span><span class="pun">.:</span><span class="lit">21069</span>
<span class="typ">Accept</span><span class="pun">:</span><span class="pln"> application</span><span class="pun">/</span><span class="pln">json</span><span class="pun">,</span><span class="pln"> text</span><span class="pun">/</span><span class="pln">javascript</span><span class="pun">,</span> <span class="pun">*</span><span class="com">/*; q=0.01</span></pre>

Accept : Tells the server whats the client want as response.

In the above case client tells,it is comfortable with josn,xml or any type.

The server response with

<pre class="prettyprint prettyprinted"><span class="pln">HTTP</span><span class="pun">/</span><span class="lit">1.1</span> <span class="lit">200</span><span class="pln"> OK
</span><span class="typ">Content</span><span class="pun">-</span><span class="typ">Type</span><span class="pun">:</span><span class="pln"> application</span><span class="pun">/</span><span class="pln">json</span><span class="pun">;</span><span class="pln"> charset</span><span class="pun">=</span><span class="pln">utf</span><span class="pun">-</span><span class="lit">8</span>
<span class="typ">Content</span><span class="pun">-</span><span class="typ">Length</span><span class="pun">:</span> <span class="lit">57</span>
<span class="typ">Connection</span><span class="pun">:</span> <span class="typ">Close</span>

<span class="pun">{</span><span class="str">"Id"</span><span class="pun">:</span><span class="lit">1</span><span class="pun">,</span><span class="str">"Name"</span><span class="pun">:</span><span class="str">"Gizmo"</span><span class="pun">,</span><span class="str">"Category"</span><span class="pun">:</span><span class="str">"Widgets"</span><span class="pun">,</span><span class="str">"Price"</span><span class="pun">:</span><span class="lit">1.99</span><span class="pun">}</span></pre>

The server makes a choice of its own of 3 types and returned the json in first place.

The process of deciding the content type between the server and client is called content -negotiation.

 

 

#Web API-Custom MediaTypeFormatters

1.You can create custom MediaTypeFormatter by inheriting abstract   BufferedMediaTypeFormatter. 

2.To add it to your web api,make changes in HttpConfiuration in Startup.cs

<pre class="prettyprint prettyprinted"><span class="pln"> config</span><span class="pun">.</span><span class="typ">Formatters</span><span class="pun">.</span><span class="typ">Add</span><span class="pun">(</span><span class="kwd">new</span> CustomFormat <span class="pun">());</span> 
</pre>

3. BufferedMediaTypeWritters  has two methods WriteToStream(write in custom format(Serialize)) and ReadFromStream(read the custom format(deserialize)).


public class CustomFormat :BufferedMediaTypeFormatter
{
public CustomFormat()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
}
public override bool CanReadType(Type type)
{
throw new NotImplementedException();
}

public override bool CanWriteType(Type type)
{
throw new NotImplementedException();
}
}

# What is REST ?

Rest(Representational State Transfer)  is recommended style/suggested pattern  which is recommend for web applications.

A System which is Restful  is  expected to meet the five principles listed below :

1.System must be represented as resource.

2.Uniform Interface (Usage of GET,POST,PUT,DELETE ) is advised to be used across the system.

3. Identify Resource by a Unique Identifier.

4. Communication via Representation (represent data by JSON/XML etc..)

5. Stateless.

# Web API : HTTP VERBS PUT VS POST

We would be aware  that both Put and Post could do both insert and update operation.However we must follow certain standard and choose either of  one verb based on scenario.

Use POST :

1.If  the insert is going to create a new resource/identifier than use POST.

2.Post is not idempotent.

what is Idempotent ?

Idempotent :  Let’s assume we are sending a  request to server with post method  “/create/1” .If we send  multiple request,it would have side effects like creating the resource twice. This might not be the desired output. Other verbs like GET,PUT are Idempotent. If we make a request to server with GET Methods ” /GET/1″ multiple times,it will yield the same result and the same with PUT  “/PUT/1”,it will only update  existing record.

 

POST /resources HTTP/1.1
The post will create new resource
/resources/newresource/

 

Use PUT :

1. If insert or update has to be performed based on existing resource .

2.Put is idempotent.

PUT /resource/<perform operation on existing_resource> 

//Update Resource or create related resource if not existing.

 

 

 

 

#Web API Processing Architechture

Over View :

In this article we will discuss the behavior of  web api when a request is made(Request) and an output it produces(Response).

Architecture :

The web API processing architecture can be divided into three Layers.

1.Hosting Layer.

2.Message Handler Pipeline Layer.

3.Controller Handler Layer.

Hosting Layer :

This layer that is responsible for exposing the web API to outside world.The Hosting layer takes care of bridging the web API and HTTP infrastructure(HTTP Listener).

Responsibilities :

1.It is also responsible for  creating HTTPRequestMessgae when HTTP Request is made and then pushing the request to next layer(Message Handler)

2.It is also responsible for converting the HTTPResponseMessage received from the Message Handler and then sending it as HTTP Response Message.

Capture.PNG

Mesaage Handler Layer:

A Message Handler acts a middle layer that performs operation over HTTPRequestMessage and HTTPResponseMessage.

For instance,when a response header  is sent from the server,you would find a attribute named “Server” which contains the server name where the request was processed. All these kind of operation are done over this layer.

There are two important  handlers in Message Handler :

1.Route Dispatcher.

2.Controller Dispatcher.

Route Dispatcher :

This is essentially where we declare the routes of web API.(Routeconfig in MVC/WEB API).

Responsibilities :

  1. When a route is made and if it has the matching route defined in Route Config ,then the Route Dispatcher forwards it to the Controller Dispatcher.
  2. If there are no match in Route,Return 404.

Controller Dispatcher :

The Controller Dispatcher is responsible for calling the respective controllers in Web API. This Dispatcher acts as a bridge between Message Handler and Controller Handler. 

ControllerHandler :

The last and final layer where we write the concrete business logic methods.This layer includes functionalities like

1.Authorization,Authentication.

2.Expection Filters.

3.Action Filters.

4.Model Binding.

Over All Architecture of WEB  API :

[Diagram]