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

WBOY
Release: 2023-09-20 20:37:15
forward
668 people have browsed it

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 -

  • text/html
  • image/png
  • application/json
When the HTTP message contains an entity body, Content The -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 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.

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;
      }
   }
}
Copy after login

Example of only returning JSON from an ASP.NET Web API service, regardless of 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 }
      );
   }
}
Copy after login

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.

我们如何在 Asp.Net WebAPI C# 中指定 MIME 类型?

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 -

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 }
      );
   }
}
Copy after login

我们如何在 Asp.Net WebAPI C# 中指定 MIME 类型?

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.

我们如何在 Asp.Net WebAPI C# 中指定 MIME 类型?

Now let’s see how to send a JSON response instead of XML when making a request 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 }
      );
   }
}
Copy after login

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.

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template