Advertisement
Beginner ASP.NET Core, Content Negotiation & Output Formatters

What is content negotiation in ASP.NET Core, and how does the Accept header influence it?

Short answer

Content negotiation is the process by which the server determines the format (JSON, XML, plain text) to return a response in, based on the client's Accept header expressing its preferences -- ASP.NET Core's [ApiController] defaults to JSON output but can serve alternate formats…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Content negotiation is the process by which the server determines the format (JSON, XML, plain text) to return a response in, based on the client's Accept header expressing its preferences -- ASP.NET Core's [ApiController] defaults to JSON output but can serve alternate formats if the corresponding output formatter is registered and the client requests it via Accept.
// Client request: Accept: application/xml
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id) => Ok(_service.GetById(id));
// Returns XML instead of the default JSON if an XML formatter is registered and requested
Real-world example
A legacy enterprise client expecting XML responses and a modern SPA expecting JSON both call the exact same endpoint, each receiving their preferred format automatically based on their respective Accept headers.
Likely follow-ups
  • What happens if the requested format isn't supported by any registered formatter?
  • How do you force a specific format regardless of the Accept header?
Related topics