What is content negotiation in Web API?
Quick Answer
Content negotiation is the server choosing the response format based on the request's Accept header. ASP.NET Core has output formatters — JSON by default, XML if you add it — and picks the best match. [Produces("application/json")] forces one; an unsupported Accept can return 406 Not Acceptable if you enable ReturnHttpNotAcceptable.
Content negotiation is the API deciding what format to send back based on the client's Accept header. ASP.NET Core has output formatters — JSON out of the box, XML if you register it — and it picks the best match. If I want to lock an action to one type I put [Produces("application/json")] on it. There's also ReturnHttpNotAcceptable which makes the server return a 406 instead of silently falling back to JSON when it can't honour the Accept header. The request side is the mirror image — input formatters pick a deserializer from the Content-Type.
- Client:
Accept: application/xml. Server: if an XML formatter is registered, it serialises to XML; otherwise falls back to JSON (or 406 if strict). - Add XML:
services.AddControllers().AddXmlSerializerFormatters(). [Produces]/[Consumes]constrain and document the types for an action.- The request body format is chosen from the
Content-Typeheader by input formatters. - You can write a custom formatter (CSV, Protobuf) by implementing
OutputFormatter.