⚙️ The Cache That Couldn’t Tell One Query String From Another
ASP.NET Core’s built-in Output Caching middleware caches a response keyed on the request path by default – it does NOT automatically vary the cached entry by query string parameters unless a policy explicitly says to. That means an endpoint like /products?category=shoes and /products?category=hats can end up sharing a single cached response, silently serving one category’s results to visitors asking for the other, with no error anywhere in the pipeline.
🔎 The Problem
builder.Services.AddOutputCache();
var app = builder.Build();
app.UseOutputCache();
app.MapGet("/products", (string category) => GetProducts(category))
.CacheOutput(); // No VaryByQuery configured
// First request: GET /products?category=shoes -> cached under key "/products"
// Second request: GET /products?category=hats -> cache HIT on the same
// key, returns the SHOES response instead of running the handler again.
// The category parameter is completely invisible to the cache key.
✅ Fix: Vary the Cache Explicitly by Every Parameter That Changes the Response
- Calling .CacheOutput(policy => policy.SetVaryByQuery(“category”)) tells the middleware to include that query parameter as part of the cache key, so each distinct value gets its own cached entry instead of colliding with every other value on the same path.
- A shared, named policy (registered once via AddOutputCache(options => options.AddPolicy(…))) applied consistently across every endpoint that varies by query string is safer than remembering SetVaryByQuery on each individual endpoint definition one at a time.
- For an endpoint where the full set of query parameters that affect output isn’t obvious at a glance, VaryByValue with a custom key-building function is worth the extra code – it guarantees the cache key reflects everything that actually changes the response, rather than trusting a manually maintained list of parameter names to stay complete.
⚠️ Why This Is Easy to Ship Without Noticing
- The bug is invisible in local testing specifically because a single developer testing one category at a time never populates the cache with a competing entry to collide with – it only appears once real traffic hits the endpoint with more than one distinct query string value within the cache’s expiration window.
- This is a newer failure mode than response caching bugs from older ASP.NET Core versions, precisely because Output Caching (introduced in .NET 7) is opt-in per endpoint via .CacheOutput() – a team migrating existing endpoints to use it can easily carry over the assumption that caching ‘just handles’ query strings the way response caching headers used to, when it explicitly requires a VaryBy configuration instead.
A cache key that ignores the query string isn’t caching the endpoint – it’s caching whichever request happened to arrive first, and handing that same answer to everyone who asked something different.




