ASP.NET Core › Caching

How does the [OutputCache] attribute's VaryByValue option let you cache based on custom, computed criteria beyond query strings or headers?

Intermediate

Answer

VaryByValue accepts a delegate computing a custom string value from the HttpContext, letting you vary cached output based on arbitrary logic (like a tenant ID derived from a claim, or a feature flag's current state) that doesn't map directly to a simple query parameter or header, giving fine-grained control over cache key composition beyond the built-in VaryByQueryKeys/VaryByHeader options.
app.MapGet("/dashboard", GetDashboard)
   .CacheOutput(policy => policy.SetVaryByValue(context => {
       var tenantId = context.User.FindFirst("tenant_id")?.Value ?? "anonymous";
       return new KeyValuePair<string, string>("tenant", tenantId);
   }));
Real-world example A multi-tenant SaaS dashboard varies its output cache by a computed tenant ID extracted from the user's claims, ensuring each tenant sees only their own cached dashboard data despite the same URL being requested by users across different tenants.

Common follow-ups: How does VaryByValue's computed key interact with other Vary options used simultaneously?;What's the performance cost of a complex VaryByValue delegate evaluated on every request?