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 own 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.
GET / HTTP/1.1
GET / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
If you want to see the output in JSON format, 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.
An Attribute helps the user to inform the framework to generate and send the output result always in given content type as follows.
The above line saying to the framework to use JSON as output format. This attribute can be decorated 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.
An Attribute helps the user to inform the framework to accept the input always in given content type as follows.
The above line saying to the framework to use JSON as input format. This attribute can be decorated 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.
services.Configure<MvcOptions>(options => options.Filters.Add(newProducesAttribute(“application/json”)) );
Hope this short article helps you to understand the topic.
Happy Coding 🙂