What is the purpose of the Vary response header, and how does ASP.NET Core's content negotiation interact with HTTP caching correctness?
Short answer
The Vary: Accept header tells caches (browsers, CDNs, reverse proxies) that a response's content differs based on the request's Accept header value, preventing a cache from incorrectly serving a JSON-cached response to a client that requested XML (or vice versa) --…
Advertisement
AModel answer
The Vary: Accept header tells caches (browsers, CDNs, reverse proxies) that a response's content differs based on the request's Accept header value, preventing a cache from incorrectly serving a JSON-cached response to a client that requested XML (or vice versa) -- content-negotiating endpoints should ensure Vary: Accept (and potentially Vary: Accept-Language for localized content) is set so intermediary caches respect the negotiation dimension when deciding whether a cached response is reusable.
// A caching proxy without seeing Vary: Accept might incorrectly serve
// a cached JSON response to a client that explicitly requested XML
Response.Headers.Vary = "Accept"; // tells caches: responses differ based on Accept header valueReal-world example
A CDN caching an API's responses without respecting the Vary: Accept header once served a JSON response to an XML-requesting client, a subtle caching bug traced back to the missing Vary header on a content-negotiating endpoint.
Likely follow-ups
- How does Vary interact with Response Caching middleware's VaryByHeader configuration?
- What other request headers commonly need to be included in Vary for correctness?
Related topics