Manage WebApi Response Using Media Types of MediaTypeFormatters

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 is 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:



Content negotiation is the process by which the ASP.NET Web API chooses the formatter to use and the media type for the response message.

Whenever we request a URL, the 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 with 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 the 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 then 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 to this link to understand CanWriteType:


WebApi: MediaTypeFormatters in WebApi

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

Kindly also visit these links to learn more about the WebApi.

Let's create a sample application and do 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:



Step 2: Click OK and choose the Web API option from the templates shown in the wizard window.



Step 3: You'll find the application structure as shown below at first sight.



Step 4: Right-click the Controllers folder in the Solution Explorer of Visual Studio. Select Add ➤Controller and provide 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.

public static IList<Employee> listEmp = new List<Employee>()
{
   new Employee()
   {
      ID = , FirstName="Sachin", LastName="Kalia"
   },
   new Employee()
   {   
      ID =002, FirstName="Dhnanjay" ,LastName="Kumar"
   },
   new Employee()
   {
      ID =003, FirstName="Ravish", LastName="Sindhwani"
   },
   new Employee()
   {
      ID =004, FirstName="Amit" ,LastName="Chaudhary"
   },
   new Employee()
   {
      ID =004, FirstName="Anshu" ,LastName="Aggarwal"
   },
};



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.



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

public class Employee
{
   public string ID { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Department { get; set; }
}

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



Great; the WebApi is up and running.

The following is the procedure to get a response of the WebApi in JSON format.

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

Now press Execute as in the following image.



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

To see the result that the WebApi has provided, you must click on the inspector tab and then TextView. You will see the output as in the following window.



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

Procedure to get response of WebApi in XML format

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

Now press Execute as in the following image.



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

To see the result that the WebApi has provided, you must click on the inspector tab and then TextView. You will see the output as in the following window.



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

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

Now press Execute as in the following image.



It will respond in JSON since it has a quality factor greater than XML.

To see the result that the WebApi has provided, you must click on the inspector tab and then TextView.You will see the output as in the following window.



Now slightly change the request and specify Accept: application/xml; q=0.8, application/json; q=0.2

in the Request Headers text box.



It will respond in XML format since XML has a higher priority than JSON in this specific request. Sounds great.

Important note: you can also identify the response after looking at the icon of the response as in the following 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 that 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 a WebApi Response using Media Types of WebApi that are very much essential from the user's perspective.

I hope it will help you somewhere down the line.

Keep coding and Smile.

Thanks.

Sachin Kalia

Up Next
    Ebook Download
    View all
    Learn
    View all