Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do we specify MIME type in Asp.Net WebAPI C#?
A media type, also called a 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, a type and a subtype. For example −
- text/html
- image/png
- application/json
When an HTTP message contains an entity-body, the Content-Type header specifies the format of the message body. This tells the receiver how to parse the contents of the message body.
When the client sends a request message, it can include an Accept header. The Accept header tells the server which media type(s) the client wants from the server.
Accept: text/html,application/xhtml+xml,application/xml
The media type determines how Web API serializes and deserializes the HTTP message body. Web API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter.
MediaTypeFormatter is an abstract class from which JsonMediaTypeFormatter and XmlMediaTypeFormatter classes inherit. JsonMediaTypeFormatter handles JSON and XmlMediaTypeFormatter handles XML. Media types are configured in the Register method of the WebApiConfig class.
Student Controller
Let's create a basic Web API controller to demonstrate MIME type handling −
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers {
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
public class StudentController : ApiController {
List<Student> students = new List<Student> {
new Student {
Id = 1,
Name = "Mark"
},
new Student {
Id = 2,
Name = "John"
}
};
public IEnumerable<Student> Get() {
return students;
}
}
}
Forcing JSON Response Only
To return only JSON from ASP.NET Web API Service irrespective of the Accept header value, remove the XML formatter −
using System.Web.Http;
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
config.MapHttpAttributeRoutes();
// Remove XML formatter to force JSON only
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Using the above code, we have removed XmlFormatter which forces ASP.NET Web API to always return JSON irrespective of the Accept header value in the client request. Even if the client sends Accept: application/xml, the service will return JSON format.
Forcing XML Response Only
To return only XML from ASP.NET Web API Service irrespective of the Accept header value, remove the JSON formatter −
using System.Web.Http;
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
config.MapHttpAttributeRoutes();
// Remove JSON formatter to force XML only
config.Formatters.Remove(config.Formatters.JsonFormatter);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
This configuration ensures that even if the client sends Accept: application/json, the Web API service will return XML format.
Returning JSON for Browser Requests
When a request is made from browser to our StudentController, the response will be in XML format by default. This is because the browser sends the accept headers as text/html by default, and Web API chooses XML as the fallback format.
To send JSON response instead of XML when the request is issued from the browser, add text/html support to the JSON formatter −
using System.Net.Http.Headers;
using System.Web.Http;
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
config.MapHttpAttributeRoutes();
// Add text/html support to JSON formatter for browser requests
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
new MediaTypeHeaderValue("text/html"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
This configuration makes the JSON formatter handle text/html requests, ensuring that browser requests receive JSON responses instead of XML.
Comparison of MIME Type Configurations
| Configuration | Accept Header | Response Format |
|---|---|---|
| Remove XML Formatter | application/xml | JSON |
| Remove JSON Formatter | application/json | XML |
| Add text/html to JSON Formatter | text/html | JSON |
| Default Configuration | application/json | JSON |
Conclusion
MIME types in ASP.NET Web API are configured through the WebApiConfig class by manipulating media type formatters. You can control response formats by removing specific formatters or adding support for additional media types to existing formatters, giving you full control over content negotiation.
