How does ASP.NET Core decide which output format to use when a client's Accept header lists multiple acceptable types with quality values (q-values)?
Short answer
The framework parses the Accept header's comma-separated list of media types, each optionally annotated with a q-value (like application/json;q=0.9,application/xml;q=0.5) indicating relative preference, and selects the highest-priority type for which a matching output formatter…
Advertisement
AModel answer
The framework parses the Accept header's comma-separated list of media types, each optionally annotated with a q-value (like application/json;q=0.9,application/xml;q=0.5) indicating relative preference, and selects the highest-priority type for which a matching output formatter is actually registered -- if no requested type has a matching formatter, behavior depends on configuration (either falling back to a default formatter or returning 406 Not Acceptable).
// Accept: application/xml;q=0.9, application/json;q=0.8
// If both XML and JSON formatters are registered, XML wins due to higher q-value
// Accept: application/pdf
// If no PDF formatter is registered: either falls back to default, or returns 406Real-world example
A client library correctly specifies application/json;q=1.0, application/xml;q=0.5 to express a strong preference for JSON while still accepting XML as an acceptable fallback if JSON somehow weren't available.
Likely follow-ups
- What does RespectBrowserAcceptHeader configuration control, and why is it off by default?
- How do you configure the API to return 406 instead of silently falling back to a default format?
Related topics