How do we specify MIME type in Asp.Net WebAPI C#?

CsharpServer Side ProgrammingProgramming

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 formurlencoded 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 from. JsonMediaTypeFormatter handles JSON and XmlMediaTypeFormatter handles XML. Media types are specified in Register method of the WebApiConfig class. Let us see some of the examples where we can play around with media types.

Student Controller

Example

using DemoWebApplication.Models;
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   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;
      }
   }
}

Example to return only JSON from ASP.NET Web API Service irrespective of the Accept header value −

public static class WebApiConfig{
   public static void Register(HttpConfiguration config){
      config.MapHttpAttributeRoutes();
      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. Use this technique when you want your service to support only JSON and not XML.

From the above output we could see irrespective of the Accept header value application/xml, the Web API service is always going to return JSON.

Example to return only XML from ASP.NET Web API Service irrespective of the Accept header value −

public static class WebApiConfig{
   public static void Register(HttpConfiguration config){
      config.MapHttpAttributeRoutes();
      config.Formatters.Remove(config.Formatters.JsonFormatter);
      config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         defaults: new { id = RouteParameter.Optional }
      );
   }
}

From the above output we could see irrespective of the Accept header value application/json, the Web API service is returning XML.

Example to return JSON instead of XML from ASP.NET Web API Service when a request is made from the browser −

When a request is made from browser to our StudentController, the response will be in XML format. This is because the browser sends the accept headers as text/html by default.

Now let us see how to send JSON response instead of XML when the request is issued from the browser.

public static class WebApiConfig{
   public static void Register(HttpConfiguration config){
      config.MapHttpAttributeRoutes();
      config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new
      MediaTypeHeaderValue("text/html"));
      config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         defaults: new { id = RouteParameter.Optional }
      );
   }
}

The below output shows the response is of type JSON when the request is fired from the browser irrespective of the accept header text/html.

raja
Published on 24-Sep-2020 16:31:13
Advertisements