liveBook · Manning

RespectBrowserAcceptHeader

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

RespectBrowserAcceptHeader is an MvcOptions setting that controls whether browser Accept headers are honored instead of applying the wildcard-format fallback.

RespectBrowserAcceptHeader is an MvcOptions setting for ASP.NET Core content negotiation. Enabling it makes MVC honor browser Accept headers instead of falling back to JSON when the header contains */*. section 20.4.2

Configure negotiation alongside the formatters your API can produce:

  • Register XML with AddXmlDataContractSerializerFormatters(). section 20.4.2
  • Set RespectBrowserAcceptHeader to true through MvcOptions. section 20.4.2
  • Set ReturnHttpNotAcceptable to true separately when unsupported formats should produce 406 instead of JSON. section 20.4.2

Negotiating XML or rejecting PNG

With XML enabled, Accept: application/xml,*/*;q=0.8 produces an XML response after RespectBrowserAcceptHeader is enabled. Accept: img/png produces 406 when ReturnHttpNotAcceptable is also enabled. section 20.4.2

Listing 20.16 Requesting an XML response with a fallback
Invoke-WebRequest http://localhost:5000/api/content/object -Headers 
@{Accept="application/xml,*/*;q=0.8"} | select @{n='Content-Type';
e={ $_.Headers."Content-Type" }}, Content

Inspect the request whose XML preference is combined with a wildcard fallback. section 20.4.2

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

How deep it goes
Explains the wildcard fallback and its configuration effect, but stops short of formatter-selection internals.
Examples
Uses XML and PNG Accept-header requests to demonstrate negotiated output, JSON fallback, and 406 rejection.
What it assumes
Assumes familiarity with ASP.NET Core MVC and formatter registration, while demonstrating the relevant negotiation settings through requests.
What you can do after
Operate/configure MVC negotiation so broad browser headers do not silently force JSON responses.
How it connects
Connects content negotiation with Accept headers, JSON formatters, XML formatters, and HTTP 406 responses.

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.