liveBook · Manning

Accept header

As explained in Pro ASP.NET Core 7, Tenth Edition

An Accept header is an HTTP request header that lists the media types a client is willing to receive in the response, optionally with relative quality preferences.

The Accept request header lists the media types a client is willing to receive. A client can give them relative preferences with q values: 1.0 is the default, while */* means it will accept any format. The header expresses a preference, not a guarantee about the response. section 20.4.2

In ASP.NET Core MVC, the available response formatters matter as much as the request. With only the default JSON formatting configured, a request for application/xml still receives JSON. Adding XML formatters with AddXmlDataContractSerializerFormatters() makes XML available for an object response. Negotiation can also be configured to return 406 Not Acceptable when no requested format is available. section 20.4.2

Prefer XML, allow JSON

Send Accept: application/xml,application/json;q=0.8 to GET /api/content/object. XML is preferred, but JSON is acceptable. If GetObject has [Produces("application/json")], that attribute rules out XML for the action, so MVC returns JSON. section 20.4.3

Listing 20.20 Requesting data
Invoke-WebRequest http://localhost:5000/api/content/object -Headers 
@{Accept="application/xml,application/json;q=0.8"} | select 
@{n='Content-Type';e={ $_.Headers."Content-Type" }}, Content

This PowerShell request tests format selection and displays both the response Content-Type and body. section 20.4.3

The same header can be read as action data rather than used only for response selection. An action parameter declared as [FromHeader] string accept receives the request’s Accept value through model binding. section 28.6.2

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains quality preferences and tests formatter behavior, including JSON fallback and XML setup, without descending into formatter internals.
Examples
Tests /api/content/object with PowerShell Accept headers and reads the Accept value through a controller parameter.
What it assumes
Assumes familiarity with ASP.NET Core controller actions and requests while explaining MIME types and q preferences.
What you can do after
Operate/configure it by enabling XML formatting, testing response types, and constraining an action to JSON with Produces.
How it connects
Connects the header to content negotiation, response formatters, the Produces attribute, and header model binding.

Also explained in

Compare how 3 books explain Accept header →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.