Understanding Produces And Consumes Attribute In MVC 6

Produces and Consumes Attributes are newly introduced in MVC 6 (ASP.NET Core) to control the content negotiation. 

What is Content Negotiation?

The process of picking the correct output format is known as Content Negotiation.

Generally, Frameworks will accept two types of input/output formats those are JSON and XML. Nowadays, every framework by default accepts and returns in JSON format because of its advantages. If the user wants to control this default behavior, he should send an Accept Header with an appropriate format in GET or POST request from a client such that Framework will make sure to use the given format.

If a user doesn’t provide any Accept-Header, then the framework will decide which format it should use based on its settings. Some of the most popular browsers such as Chrome and Firefox will by default add Accept Header as application/xml and that is the reason when we call the web API from the browser will display the output in XML format if we don’t explicitly set the output format as JSON.

Below are the sample requests generated from Chrome and IE where can observe the Accept Headers for these two browsers.

Chrome

GET / HTTP/1.1
Host: localhost:8080
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

IE

GET / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*

If you want to see the output in JSON format, it's preferred to use any tools like fiddler, browser dev tools etc.

To control this and let the user be given full control of how to receive and sent the data format, Produces and Consumes Attribute is introduced in new ASP.NET MVC Core.

Produces Attribute

This attribute helps the user to inform the framework to generate and send the output result always in given content type as follows.

  1. [Produces("application/json")]  

The above line is saying to the framework to use JSON as output format. This attribute can be decorated at controller level as well as Action level. Action level will be taken as the first priority if it is declared at both controller level as well as Action level.

Consumes Attribute

An Attribute helps the user to inform the framework to accept the input always in given content type as follows.

  1. [Consumes("application/json")]  

The above line is saying to the framework to use JSON as input format. This attribute can be decorated at controller level as well as Action level. Action level will be taken as the first priority if it is declared at both controller level as well as Action level.

If you want to control it globally, you can set this while configuring MVC in ConfigureServices method as follows.

  1. Configure<MvcOptions>(options =>  
  2.    Filters.Add(newProducesAttribute(“application/json”))  
  3. );  

Hope this short article helps you to understand the topic.

Happy Coding.


Similar Articles