liveBook · Manning

Accept header

As explained in ASP.NET Core in Action, 3e

An Accept header is an HTTP request header that lists the media types a client can understand and may rank by preference.

An Accept header tells an HTTP server which media types a client can handle. During content negotiation, the server selects a supported format and identifies it with the response's Content-Type header. section 20.5

Ranking preferred formats

The header `application/json,text/xml;q=0.9,text/plain;q=0.6` accepts JSON, XML, and plain text. JSON has the highest preference because its default weighting is 1.0. section 20.5

ASP.NET Core web API controllers normally support JSON, text/plain, and text/html. Adding an XML output formatter makes a request with `text/xml` return XML instead of the default JSON. Without a usable Accept value, strings generally become text/plain and other models typically use the first suitable formatter. section 20.5.1 section 20.5.2

Browser requests are a notable exception: when Accept contains `*/*`, ASP.NET Core normally ignores content negotiation and uses its default formatter. Set `RespectBrowserAcceptHeader` to true when browser preferences must be honored. section 20.5.2

Listing 20.14 Customizing MVC to respect the browser’s Accept header in web APIs
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddControllers(options =>                           #1
{
    options.RespectBrowserAcceptHeader = true;                       #2
    options.OutputFormatters.RemoveType<StringOutputFormatter>();    #3
});
#1 AddControllers has an overload that takes a lambda function.
#2 False by default; several other properties are also available to be set.
#3 Removes the output formatter that formats strings as text/plain

Use the MVC configuration listing to respect browser Accept headers and remove the string formatter that produces text/plain. section 20.5.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains MIME-type weighting, formatter selection, defaults, browser exceptions, and XML configuration, but defers custom formatter implementation.
Examples
Uses weighted JSON, XML, and plain-text preferences, plus browser requests, XML formatter configuration, and a cars-controller response.
What it assumes
Assumes HTTP request and response headers, while introducing MIME types, formatters, and content negotiation.
What you can do after
Operate/configure ASP.NET Core controllers to request, produce, and troubleshoot JSON or XML response formats.
How it connects
Connects content negotiation with Content-Type, MIME types, output formatters, JSON, XML, and HTTP API controllers.

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 ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.