In this article, I am going to discuss the Media Type Formatter in Web API with examples. Please read our previous article before proceeding to this article where we discussed Content Negotiation in Web API.
Note: We are going to work with the same example that we started in ASP.NET Web API using the SQL Server article. So please read that article before proceeding to this article.
What are MediaTypeFormatters in Web API?
As we have seen in the previous article that the Web API handles the JSON and XML formats data based on the Accept and Content-Type headers. But, the important question is how does it handle these different formats? The answer is: By using Media-Type formatters.
The Media type formatters are the classes that are responsible for serializing the request/response data so that the Web API Framework can understand the request data format and also send data in the format which the client expects. ASP.NET Web API includes the following built-in media type formatters.
How to Retrieve the Built-in Media Type Formatters in ASP.NET Web API?
The Web API Framework includes the above-listed media type formatter classes by default. However, you can also add, remove or change the order of the formatters. The following example demonstrates an HTTP Get method that returns all built-in formatter classes.
In the above example, the GlobalConfiguration.Configuration.Formatters returns the MediaTypeFormatterCollection that includes all the formatter classes. The above example returns the names of all the formatter classes as shown in the image below.
Alternatively, the MediaTypeFormatterCollection class defines convenience properties that provide direct access to three of the four built-in media type formatters. The following example shows retrieving the media type formatters using MediaTypeFormatterCollection’s properties.
The above example returns the following response to the browser.
Understanding Media Type Formatters with an example
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 in Web API can be either JSON or XML. A media type formatter that 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:
The above method returns a CLR object of Employee type. In order to return the data contained in the Employee object to the client, the Employee object needs to be serialized. The serialization in ASP.NET Web API application is generally performed by the MediaTypeFormatter.
The Web API Media Type Formatters serializes the object which is going to be returned from the action method into either JSON or XML. Once the Web API Media Type Formatters serializes the data into XML or JSON then these JSON or XML data written into the response message body.
The Web API media type formatters that serialize the object into the JSON and XML are JsonMediaTypeFormatter and XmlMediaTypeFormatter respectively. Both the classes are deriving from MediaTypeFormatter class. The process through which the MediaTypeFormatter is chosen is called content negotiation which we discussed in our previous article in detail.
What is Web API MediaTypeFormatter?
The Web API MediaTypeFormatter is an abstract class from which the JsonMediaTypeFormatter and XmlMediaTypeFormatter classes are inherited. JsonMediaTypeFormatter handles the JSON request and response where the XmlMediaTypeFormatter handles the XML request and response.
A resource can have one or more representations. When we issue a GET request to retrieve a resource, such as an employee with ID 1, the response message contains the representation of the resource, for example, 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.
By default, the Web API framework supports two media types: JSON and XML. When you issue a request with Accept: application/json, then the response message will be JSON and the Content-Type will be set to application/json. Similarly, if you issue a request with Accept: application/xml, then the response message will be XML and the Content-Type will be set to application/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, consider the below header
Accept: application/json; q=0.8, application/xml;q=0.9
Here, the response message will be in XML format because the application/xml has a quality value of 0.9, which is higher than the quality value of 0.8 specified for application/json.
How to return the data in JSON format from Web API Service irrespective of the Accept header value?
Include the following line in Register() method of WebApiConfig.cs file in the App_Start folder. This line of code completely removes XmlFormatter which forces ASP.NET Web API to always return JSON irrespective of the Accept header value in the client request. Use this technique when you want your service to support only JSON and not XML.
config.Formatters.Remove(config.Formatters.XmlFormatter); With this change, irrespective of the Accept header value (application/xml or application/json), the Web API service is always going to return JSON.
How to return the data in XML format from Web API Service irrespective of the Accept header value?
Include the following line in Register() method of WebApiConfig.cs file in the App_Start folder. This line of code completely removes JsonFormatter which forces ASP.NET Web API to always return XML irrespective of the Accept header value in the client request. Use this technique when you want your service to support only XML and not JSON.
config.Formatters.Remove(config.Formatters.JsonFormatter); With this change, irrespective of the Accept header value (application/xml or application/json), the Web API service is always going to return XML.
How to return JSON instead of XML from ASP.NET Web API Service when a request is made from the browser?
So here is what we want the service to do
Approach 2: Include the following class in WebApiConfig.cs file in the App_Start folder.
Register Custom formatter.
Place the following line in the Register() method of WebApiConfig.cs file in the App_Start folder.
With these 2 changes, when a request is issued from the browser we will get JSON formatted data and the Content-Type header of the response is also set to application/json. If we are using tools like Fiddler and if we set Accept header to application/xml we will still get XML formatted data.
Summary:
I Hope this post will be helpful to understand the concept of Media Type Formatter in Web API.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Note: We are going to work with the same example that we started in ASP.NET Web API using the SQL Server article. So please read that article before proceeding to this article.
What are MediaTypeFormatters in Web API?
As we have seen in the previous article that the Web API handles the JSON and XML formats data based on the Accept and Content-Type headers. But, the important question is how does it handle these different formats? The answer is: By using Media-Type formatters.
The Media type formatters are the classes that are responsible for serializing the request/response data so that the Web API Framework can understand the request data format and also send data in the format which the client expects. ASP.NET Web API includes the following built-in media type formatters.
How to Retrieve the Built-in Media Type Formatters in ASP.NET Web API?
The Web API Framework includes the above-listed media type formatter classes by default. However, you can also add, remove or change the order of the formatters. The following example demonstrates an HTTP Get method that returns all built-in formatter classes.
public IEnumerable<string> Get() { IList<string> formatters = new List<string>(); foreach (var item in GlobalConfiguration.Configuration.Formatters) { formatters.Add(item.ToString()); } return formatters.AsEnumerable<string>(); }
In the above example, the GlobalConfiguration.Configuration.Formatters returns the MediaTypeFormatterCollection that includes all the formatter classes. The above example returns the names of all the formatter classes as shown in the image below.
Alternatively, the MediaTypeFormatterCollection class defines convenience properties that provide direct access to three of the four built-in media type formatters. The following example shows retrieving the media type formatters using MediaTypeFormatterCollection’s properties.
public IEnumerable<string> Get() { IList<string> formatters = new List<string>(); formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter.GetType().FullName); formatters.Add(GlobalConfiguration.Configuration.Formatters.XmlFormatter.GetType().FullName); formatters.Add(GlobalConfiguration.Configuration.Formatters.FormUrlEncodedFormatter.GetType().FullName); return formatters.AsEnumerable<string>(); }
The above example returns the following response to the browser.
Understanding Media Type Formatters with an example
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 in Web API can be either JSON or XML. A media type formatter that 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) { using (EmployeeDBContext dbContext = new EmployeeDBContext()) { return dbContext.Employees.FirstOrDefault(e => e.ID == id); } }
The above method returns a CLR object of Employee type. In order to return the data contained in the Employee object to the client, the Employee object needs to be serialized. The serialization in ASP.NET Web API application is generally performed by the MediaTypeFormatter.
The Web API Media Type Formatters serializes the object which is going to be returned from the action method into either JSON or XML. Once the Web API Media Type Formatters serializes the data into XML or JSON then these JSON or XML data written into the response message body.
The Web API media type formatters that serialize the object into the JSON and XML are JsonMediaTypeFormatter and XmlMediaTypeFormatter respectively. Both the classes are deriving from MediaTypeFormatter class. The process through which the MediaTypeFormatter is chosen is called content negotiation which we discussed in our previous article in detail.
What is Web API MediaTypeFormatter?
The Web API MediaTypeFormatter is an abstract class from which the JsonMediaTypeFormatter and XmlMediaTypeFormatter classes are inherited. JsonMediaTypeFormatter handles the JSON request and response where the XmlMediaTypeFormatter handles the XML request and response.
A resource can have one or more representations. When we issue a GET request to retrieve a resource, such as an employee with ID 1, the response message contains the representation of the resource, for example, 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.
By default, the Web API framework supports two media types: JSON and XML. When you issue a request with Accept: application/json, then the response message will be JSON and the Content-Type will be set to application/json. Similarly, if you issue a request with Accept: application/xml, then the response message will be XML and the Content-Type will be set to application/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, consider the below header
Accept: application/json; q=0.8, application/xml;q=0.9
Here, the response message will be in XML format because the application/xml has a quality value of 0.9, which is higher than the quality value of 0.8 specified for application/json.
How to return the data in JSON format from Web API Service irrespective of the Accept header value?
Include the following line in Register() method of WebApiConfig.cs file in the App_Start folder. This line of code completely removes XmlFormatter which forces ASP.NET Web API to always return JSON irrespective of the Accept header value in the client request. Use this technique when you want your service to support only JSON and not XML.
config.Formatters.Remove(config.Formatters.XmlFormatter); With this change, irrespective of the Accept header value (application/xml or application/json), the Web API service is always going to return JSON.
How to return the data in XML format from Web API Service irrespective of the Accept header value?
Include the following line in Register() method of WebApiConfig.cs file in the App_Start folder. This line of code completely removes JsonFormatter which forces ASP.NET Web API to always return XML irrespective of the Accept header value in the client request. Use this technique when you want your service to support only XML and not JSON.
config.Formatters.Remove(config.Formatters.JsonFormatter); With this change, irrespective of the Accept header value (application/xml or application/json), the Web API service is always going to return XML.
How to return JSON instead of XML from ASP.NET Web API Service when a request is made from the browser?
So here is what we want the service to do
- When a request is issued from the browser, the web API service should return JSON instead of XML.
- When a request is issued from a tool like a fiddler the Accept header value should be respected. This means if the Accept header is set to application/xml the service should return XML and if it is set to application/JSON the service should return JSON.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));
Approach 2: Include the following class in WebApiConfig.cs file in the App_Start folder.
using System; using System.Net.Http.Formatting; using System.Net.Http.Headers; public class CustomJsonFormatter : JsonMediaTypeFormatter { public CustomJsonFormatter() { this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); } public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { base.SetDefaultContentHeaders(type, headers, mediaType); headers.ContentType = new MediaTypeHeaderValue("application/json"); } }
Register Custom formatter.
Place the following line in the Register() method of WebApiConfig.cs file in the App_Start folder.
config.Formatters.Add(new CustomJsonFormatter());
With these 2 changes, when a request is issued from the browser we will get JSON formatted data and the Content-Type header of the response is also set to application/json. If we are using tools like Fiddler and if we set Accept header to application/xml we will still get XML formatted data.
Summary:
I Hope this post will be helpful to understand the concept of Media Type Formatter in Web API.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.