Thursday, April 24, 2014

WebApi: MediaTypeFormatters in WebApi

WebApi: MediaTypeFormatters in WebApi

In this article I’ll share my Media Type formatting in WebApi.

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:

public Employee Get(int id)

{

return list.First(e => e.Id == id);  clip_image002   clip_image001

}

This method returns a CLR object of type Employee. In order for the data contained in this object to be returned to the client in the HTTP response message, the object must be serialized. The MediaTypeFormatter object inthe ASP.NET Web API pipeline performs this serialization. It serializes the object returned by the action method into JSON or XML, which is then written into the response message body. The out-of-box media formatters that produce JSON and XML are respectively JsonMediaTypeFormatter and XmlMediaTypeFormatter, both deriving from MediaTypeFormatter. The process through which the MediaTypeFormatter is chosen is called content negotiation, also known as conneg.

A resource can have one or more representations. When you issue a GET to retrieve a resource, such as the employee with ID 12345, the response message contains the representation of the resource e.g. any value that specific action returns. The Web API indicates how the resource is represented in the response through the Content-Type response header. The Accept request header can be used by a client to indicate the set of preferred representations for the resource in the response.

Default the ASP.NET Web API framework supports two media or content types: JSON and XML.If you send a request with Accept: application/json, the response message will be JSON and Content-Type will be application/json. Similarly, if you send a request with Accept: application/xml, the response message will be XML. You can also specify a quality value indicating the relative preference. The range is 0–1, with 0 being unacceptable and 1 being the most preferred. The default value is 1. For example, if you send the request header Accept: application/json; q=0.8, application/xml;q=0.9, the response message will be XML,because application/xml has a quality value of 0.9, which is higher than the quality value of 0.8 specified for application/json.

Now we take an example and list out the default MediaTypeFormatters:

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 and using ASP.NET MVC 4 Web Application and named It with your choice as I gave WebApiDemo shown in depict image below:

clip_image004

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

clip_image006

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

clip_image008

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.

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



clip_image010

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.

clip_image012

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


   1:  public class Employee
   2:  {
   3:   
   4:  public string ID { get; set; }
   5:   
   6:  public string FirstName { get; set; }
   7:   
   8:  public string LastName { get; set; }
   9:   
  10:  public string Department { get; set; }
  11:   
  12:  }
  13:   


Modify the Register method in WebApiConfig in the App_Start folder and add some code segment into this to list out the default MediaTypeFormatters as shown in below image:


clip_image014

Press F5 and run your application it will show the below image:

clip_image016

Great WebApi is up and running.

Now look at the output window of your application, it gives you the details of each line which we’ve placed into the WebApiConfig.cs file.

clip_image017

From the serialization point of view, the last two media type formatters can be ignored, since they cannot write any type. The first two, JsonMediaTypeFormatter and XmlMediaTypeFormatter, are the important ones. They are the media formatters that produce JSON and XML resource representations in the response

Conclusion: In this article we looked into default MediaTypeFormatters of WebApi, which are very much essentials from user perspective.


You can touch base with me on DotnetPiper.

Hope it will help you somewhere down the line J

Keep coding and Smile Smile

Thanks

Sachin Kalia





3 comments :

  1. Replies
    1. không có khả năng làm được.

      - Chủ nhân, ta đã tìm hiểu địa chỉ của cửa hàng Tam tinh môn rồi, nó tổng công 18 cái, trong đó lớn nhất ở ngay tại phía trước không xa.

      Thanh bối ma ngưu nói.
      đồ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ó
      - Ân, chuẩn bị động thủ đi, các ngươi đi theo ta.

      Nhạc Thành nói, lập tức đưa cho sáu đầu ma thú mỗi người năm trữ vật nhẫn.

      - Chủ nhân, ngươi lấy trữ vật nhẫn cho chúng ta làm cái gì.

      Thanh bối ma ngưu nghi hoặc nhìn Nhạc Thành hỏi, cho dù cấp cho cũng không dùng nhiều như vậy đi.

      - Các ngươi, là ai…

      Nhạc thành hơi thở dài một hơi, chuyện tốt Khiếu Thiên hổ cùng Tử điện mãng chúng nó thông minh, mấy đầu thất giai ma thú đại khái ở kết giới thời gian quá dài, cũng không biết đến hang ổ của Tam tinh môn cướp sạch sao.

      Delete