Media type, also called MIME type, identifies the format of a piece of data. In HTTP, media types describe the format of the message body. A media type consists of two strings: type and subtype. For example -
When the client sends a request message, it can include the Accept header. The Accept header tells the server which media type the client expects from the server.
Accepts: text/html,application/xhtml xml,application/xml p>
The media type determines how the Web API serializes and deserializes the HTTP message body. Web API has built-in support for XML, JSON, BSON, and formurlencoded data, and you can support other media types by writing media formatters.
MediaTypeFormatter is an abstract class from which the JsonMediaTypeFormatter and XmlMediaTypeFormatter classes inherit. JsonMediaTypeFormatter handles JSON and XmlMediaTypeFormatter handles XML. The media type is specified in the Register method of the WebApiConfig class. Let's look at some examples where media types can be used.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Example of only returning JSON from an ASP.NET Web API service, regardless of Accept header value -
1 2 3 4 5 6 7 8 9 10 11 |
|
With the above code, we removed the XmlFormatter, which forces ASP.NET Web API to always return JSON regardless of the Accept header value in the client request. Use this technique when you want your service to support only JSON instead of XML.
From the above output we can see that the Web API service always returns JSON regardless of the Accept header value application/xml.
Example of returning only XML from ASP.NET Web API service regardless of Accept header value -
1 2 3 4 5 6 7 8 9 10 11 |
|
From the above output we can see that whatever the Accept header value application/json is, the Web API service returns XML.
Example of returning JSON instead of XML from ASP.NET Web API service in the following situations Browser makes request -
When the browser makes a request to our StudentController, the response will be in XML format. This is because browsers send accept headers as text/html by default.
Now let’s see how to send a JSON response instead of XML when making a request from the browser.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The output below shows that when the request is triggered from the browser, the response is of type JSON regardless of the accept header text/html.
The above is the detailed content of How do we specify MIME type in Asp.Net WebAPI C#?. For more information, please follow other related articles on the PHP Chinese website!