⚙️ Fix Response Caching Ignoring a Vary Header
The built-in Response Caching Middleware keys its cache entries off the response’s own Vary header, not off some separate configuration the middleware maintains independently – so whatever Vary value happened to be present on the first response cached for a given URL is the one every subsequent request is bucketed against, for as long as that entry lives. If the header that actually varies the response is only set conditionally in application code – Vary: Accept-Language added only when a translation exists, and omitted on a fallback to the default language – the very first cache miss for that URL can be exactly the request that falls into the fallback branch, caching a response with no Vary header at all, and every later request regardless of its own Accept-Language gets served that same cached default.
🔎 The Problem
[HttpGet("/welcome")]
[ResponseCache(Duration = 300)]
public IActionResult Welcome()
{
var lang = Request.Headers.AcceptLanguage.ToString();
if (_translations.TryGetValue(lang, out var text))
{
Response.Headers.Vary = "Accept-Language"; // only set on this branch
return Content(text);
}
return Content(_translations["en"]); // fallback: Vary never set here
}
// First request ever made: Accept-Language: tr-TR, no Turkish translation
// yet configured -> falls to the "en" branch -> cached WITHOUT a Vary
// header at all
// Every later request (Accept-Language: de-DE, fr-FR, whatever) hits the
// same cache entry and gets the English fallback text, because the
// middleware has no Vary header on record telling it to key by language
✅ Fix: Set Vary on Every Code Path
- Set the Vary header unconditionally, on every code path through the action including the fallback branch, so the middleware’s cache key always accounts for Accept-Language regardless of which branch happened to produce the very first cached response.
- Alternatively, configure [ResponseCache(VaryByHeader = “Accept-Language”)] directly on the attribute, which applies the Vary behavior declaratively at the action level rather than depending on the action remembering to set the header on every branch.
- When adding response caching to any endpoint whose output depends on a request header, write a test that hits the endpoint twice with two different values of that header, before and after a cache is warm, and assert the two responses actually differ.
🚨 Why This Is Dangerous
A caching bug that depends on which request happens to arrive first is close to impossible to reproduce reliably – it can pass every manual test, where you naturally try the common case first, and only surface in production once real traffic in an unpredictable order populates the cache with the wrong entry.
Response Caching Middleware isn’t ignoring the Vary header – it’s only ever as good as whichever response happened to set it first, for every request after that one.




