Tuesday, April 29, 2014

Manage WebApi Response using Media Types of MediaTypeFormatters

In this article I’ll explore different ways to manage Manage WebApi Response using Media Types with help of Media Type Formatters.

From the ASP.NET Web API perspective, serialization is the process of translating a .NET Common Language Runtime (CLR) type into a format that can be transmitted over HTTP. The default format I are either JSON or XML

A media type formatter, which is an object of type MediaTypeFormatter, performs the serialization in the ASP.NET Web API pipeline. Consider a simple action method handling GET in an ApiController:

 

  1: [HttpGet]
  2: public Employee FetchEmployeeById (int id)
  3: {
  4: return list.First(e => e.Id == id);
  5: }
  6: 
Content negotiation is the process by which ASP.NET Web API chooses the formatter to use and the media type for the response message.

Whenever we request a url, WebApi checks the following four items before deciding on the media formatter to use.

1. Media type mapping: Every MediaTypeFormatter has a collection of MediaTypeMapping values. A MediaTypeMapping allows you to map the request or response messages that have certain characteristics to a media-type. There are four out-of-box media type mappings: QueryStringMapping, UriPathExtensionMapping, RequestHeaderMapping, and MediaRangeMapping. These respectively map a query string parameter, URI path extension, request header, and media range to a media type. As an example, defining a QueryStringMapping with a parameter name of fmt and a value of json and media-type of application/json will let ASP.NET Web API choose JsonMediaTypeFormatter, if the query string has a field fmt with a value of json, such as this: http://localhost:57888/api/employees/001?fmt=json.

2. Media type as specified in the Accept request header.

3. Media type as specified in the Content-Type request header.

4. If there is no match so far, the conneg algorithm goes through the MediaTypeFormatter Objects defined in the config and checks if a formatter can serialize the type by calling the CanWriteType method. The first formatter that can serialize the type is chosen.Kindly refer this link to understand CanWriteType as given below:

WebApi: MediaTypeFormatters in WebApi

Now we use an example and see the behavior of request with Media Type.

Kindly can also visit these links to know more about WebApi.

WEBAPI: EXECUTION OF RPCSTYLE ACTION METHOD IN WEBAPI USING MVC4

WEBAPI PATCH UPDATE USING FROMBODY PARAMETER IN WEBAPI USING MVC4 TEMPLATE

WebApi Configuration over Convention using MVC4 template

Let’s create a sample application and achieve this step by step.

Step 1: Let's first create a sample web application using an ASP.NET MVC 4 Web Application and name it as you choose; I used WebApiDemo as shown in the image below:


image


 


Step2: Click ok and choose Web API option from the templates shown in wizard window.

image


Step3: You’ll find the application structure as shown below at first sight.

image

 

Step 4: Right-click the Controllers folder in the Solution Explorer of Visual Studio. Select Add ➤Controller and give a name of EmployeesController for the controller. Leave the option Empty API Controller selected in the Template dropdown and click Add, as shown in Figure below. Notice that the generated controller class inherits from ApiController, a class that is part of the ASP.NET Web API framework.Kinldy add the following code into EmployeesController class.

image

 

  1: public static IList<Employee> listEmp = new List<Employee>()
  2:         {
  3:             new Employee()
  4:             {
  5:                 ID =    , FirstName="Sachin", LastName="Kalia"
  6:             },
  7:              new Employee()
  8:             {
  9:                 ID =002, FirstName="Dhnanjay" ,LastName="Kumar"
 10:             },
 11:             new Employee()
 12:             {
 13:                 ID =003, FirstName="Ravish", LastName="Sindhwani"
 14:             },
 15:              new Employee()
 16:             {
 17:                 ID =004, FirstName="Amit" ,LastName="Chaudhary"
 18:             },
 19:              new Employee()
 20:             {
 21:                 ID =004, FirstName="Anshu" ,LastName="Aggarwal"
 22:             },
 23: 
 24:         };
 25: 

Step 5: Right-click the Models folder in the Solution Explorer of Visual Studio. Select Add ➤ Class

to add a new class with a name of Employee.

image

 

After creating the Employee.cs class, kindly add the following code into this class.

  1: public class Employee
  2: {
  3: public string ID { get; set; }
  4: public string FirstName { get; set; }
  5: public string LastName { get; set; }
  6: public string Department { get; set; }
  7: }
  8: 
  9: 
Press F5 and run your application it will show the below image:

image

 

Great WebApi is up and running.

Steps to get response of WebApi in Json format.

Open Web proxy tool fiddler and paste the following URL (http://localhost:57888/api/Employees/001) in composer tab and specifying Accept: application/json in the Request Headers text box.

image

 

It will respond in json format after accepting the Accept: application/json.To see the result which WebApi has responded, you require clicking on the inspector tab and then TextView.You will see the output as following window

 

image

Now we change the Media Type to Accept: application/xml, after putting this in the request WebApi will respond in xml format. Let’s see in example.

Steps to get response of WebApi in XML format:


Open Web proxy tool fiddler and paste the following URL (http://localhost:57888/api/Employees/001) in composer tab specifying Accept: application/xml in the Request Headers text box.

Now press Execute as depicted below in image.

image

It will respond in xml format after accepting the Accept: application/xml.

To see the result which WebApi has responded, you require clicking on the inspector tab and then TextView.You will see the output as following window.

image

Steps to get response of WebApi on basis of quality factor:

Open Web proxy tool fiddler and paste the following URL (http://localhost:57888/api/Employees/001) in composer tab and specifying Accept: application/xml;q=0.2, application/json;q=0.8 in the Request Headers text box.

Now press Execute as depicted below in image.

image

It will respond in json as it has quality factor greater than xml.

To see the result which WebApi has responded, you require clicking on the inspector tab and then TextView.You will see the output as following window

image

Now slightly change the request and specifying Accept: application/xml; q=0.8, application/json; q=0.2In the Request Headers text box.

image

It will respond in xml format due to xml has higher priority than json in this specific request. Sounds great.

Important note: you can also identify the response after looking at the icon of response as shown in below image.

image

 

Difference between accept and content-type http headers?

As you correctly note, the Accept header is used by HTTP clients to tell the server what content types they'll accept. The server will then send back a response, which will include a Content-Type header telling the client what the content type of the returned content actually is.However, as you may have noticed, HTTP requests can also contain Content-Type headers. Why? Well, think about POST or PUT requests. With those request types, the client is actually sending a bunch of data to the server as part of the request, and the Content-Type header tells the server what the data actually is (and thus determines how the server will parse it).In particular, for a typical POST request resulting from an HTML form submission, the Content-Type of the request will normally be either application/x-www-form-urlencoded or multipart/form-data.

Conclusion: In this article we looked into how to Manage WebApi Response using Media Types of WebApi those are very much essential from the user's perspective.

Hope it will help you somewhere down the line J

Keep coding and Smile Smile

Thanks

Sachin Kalia

1 comment :

  1. ngưu cùng bốn đầu ma lang còn lại hóa thành hình người đi theo bên cạnh Tứ sí ma ưng, tất cđồng tâm
    game mu
    cho thuê nhà trọ
    cho thuê phòng trọ
    nhac san cuc manh
    số điện thoại tư vấn pháp luật miễn phí
    văn phòng luật
    tổng đài tư vấn pháp luật
    dịch vụ thành lập công ty trọn gói
    http://we-cooking.com/
    chém gióả nhanh chóng đi về phía trước bay qm ra bảo tàng này thật đúng là hấp dẫn nhiều người, tự nhiên có nhiều như vậy tìm kiếm ta.

    Nhạc thành lẩm bẩm nói, nhìn đến phụ cận không ít người ở bên trong sơn mạch đang tìm mình, Nhạc Thành, Doanh Thi, Thanh bối ma ngưu cùng đám ma lang bay đi Tần Hoa thành.

    Bốn ngày hôm sau, Tần Hoa thành náo nhiệt cũng hiện ra, Tần hoa thành tuy rằng kém Cự Thạch thành, nhưng so với lang thành đều lớn hơn, trình độ náo nhiệt cũng không nói chơi, mà nơi này cũng là trụ sở của Tam Tinh môn.

    Tam Tinh môn ở trong Tần Hoa thành tổng cộng có mười tám cửa hàng, ở trong Tần Hoa thành cũng là thực lực cao nhất, về Tam tinh môn cường giả toàn bộ bị ngã xuống, tin tức này bên ngoài người cũng không biết, nếu không Tam Tinh môn ở Tần Hoa thành thực lực sợ sớm đã có người nghĩ cách rồi.

    Dù sao ở trong Tần Hoa thành thế lực cao nhất không chỉ có Tam Tinh môn một nhà mà thôi, mặt khác còn có không ít thế lực lớn cũng tồn tại trong đó, mỗi một cổ thế lực đều không kém gì Tam tinh môn, ai muốn chân chính xưng bá ở Tần Hoa thành nhưng đều

    ReplyDelete