skip to content

How does ASP.NET Core output caching build its cache key by default, and what do SetVaryByQuery and VaryByValue change about it?

level: middleimportance: should knowfreq 37%

answer

  1. method, scheme, host, path
  2. paths compared case-insensitively
  3. default query rule is *
  4. SetVaryByQuery replaces the wildcard
  5. VaryByValue adds a computed pair

basics

~20 s

The key joins method, scheme, host and path (case-insensitive) plus, by default, every query-string key and value. SetVaryByQuery narrows the query part to named keys; VaryByValue adds a key/value pair computed from HttpContext, such as the UI culture.

solid answer

~40 s

The default key provider joins the request method, scheme, host (because `CacheVaryByRules.VaryByHost` defaults to `true`), path base and path, upper-cased unless `OutputCacheOptions.UseCaseSensitivePaths` is set, followed by vary segments. The default policy sets the query rule to `*`, so every distinct query string, tracking parameters such as `utm_source` included, gets its own entry. `SetVaryByQuery("day", "stage")` replaces that wildcard with just those keys, so other parameters stop splitting the cache; they must then not affect the output, or users get the wrong page. `SetVaryByHeader` and `SetVaryByRouteValue` add header and route values, and `VaryByValue` adds a pair computed per request, e.g. `ctx => new("culture", CultureInfo.CurrentUICulture.Name)`. These rules shape only the server's key; the middleware adds no `Vary` response header.

code

csharp · 11 lines
csharp
builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("Listings", b => b
        .Expire(TimeSpan.FromMinutes(10))
        .SetVaryByQuery("day", "stage")
        .VaryByValue(ctx => new("culture", CultureInfo.CurrentUICulture.Name)));
});

app.MapGet("/lineup", (string? day, string? stage, FestivalDb db) =>
        Lineup.QueryAsync(db, day, stage))
   .CacheOutput("Listings");

go deeper

for a junior

Remember that the key is method, host and path plus, by default, the whole query string, and that SetVaryByQuery narrows it to the keys you name.

for a middle

Walk through the key parts and the vary segments, the difference between the builder methods and the attribute properties, and what VaryByValue is for.

for a senior

Discuss the two failure directions: a key too wide fragments the cache and invites cache filling, a key too narrow serves the wrong variant. Note that no Vary header is emitted for downstream caches.

for a principal

Treat the cache key as a contract between the handler and the policy, and decide who owns keeping them in sync as an endpoint gains new parameters.

## The parts of an output cache key When a policy allows caching, ASP.NET Core's `OutputCacheKeyProvider` builds a string key from the request. In order it appends: 1. an optional **prefix** set by `SetCacheKeyPrefix(...)`; 2. the **method**, upper-cased (`GET` and `HEAD` get separate entries); 3. the **scheme** (`HTTP` or `HTTPS`); 4. the **host and port**, because `CacheVaryByRules.VaryByHost` is `true` by default; `SetVaryByHost(false)` replaces it with a wildcard so all host names share entries; 5. the **path base and path**, upper-cased unless `OutputCacheOptions.UseCaseSensitivePaths` is `true`; 6. **vary segments** for headers, query keys, route values and custom values, each only when a rule asks for them. Anything not in that list does not distinguish two requests. Two requests that produce the same key share one entry. Notably, the following are **not** in the default key: - **cookies**, including authentication and culture cookies; - **request headers** such as `Accept`, `Accept-Language` or `Accept-Encoding`; - the **request body**; - the **user**, since authenticated requests are refused rather than keyed. That is why a festival site serving English and German line-ups from one URL, chosen by `Accept-Language` or by a culture cookie, must add a vary rule. Without one, whichever language was requested first is replayed to everyone for the entry's lifetime. The same applies to content negotiation: an endpoint that returns JSON or CSV based on `Accept` needs `SetVaryByHeader("Accept")`. ## The default: vary by every query key The default policy sets `CacheVaryByRules.QueryKeys` to `*`. With a festival's listing endpoint: | Request | Entry | |---|---| | `/lineup?day=fri` | A | | `/lineup?day=fri&utm_source=mail` | B | | `/lineup?day=fri&utm_source=app` | C | | `/LINEUP?day=fri` | A (path case ignored) | Correct, but wasteful: marketing parameters fragment the cache, and an attacker can fill it with random query strings until the store's `SizeLimit` is reached. ## Narrowing with SetVaryByQuery ```csharp options.AddPolicy("Listings", b => b .Expire(TimeSpan.FromMinutes(10)) .SetVaryByQuery("day", "stage")); ``` `SetVaryByQuery` **replaces** the default wildcard with the listed keys (if another policy already listed keys, it appends to them). Now `utm_source` no longer matters and requests A, B and C share an entry. The cost is a correctness obligation: if the handler also reads `genre`, two requests differing only in `genre` would share one response. Passing an empty array removes the query string from the key entirely. The attribute equivalent is `[OutputCache(VaryByQueryKeys = new[] { "day", "stage" })]`. ## Other dimensions | Builder method | Attribute property | Adds to the key | |---|---|---| | `SetVaryByHeader("Accept-Language")` | `VaryByHeaderNames` | that request header's value | | `SetVaryByRouteValue("id")` | `VaryByRouteValueNames` | the named route values | | `VaryByValue(...)` | none | a computed key/value pair | | `SetCacheKeyPrefix(...)` | none | a prefix, fixed or computed | | `SetVaryByHost(false)` | none | drops the host | ## VaryByValue in practice `VaryByValue` covers whatever cannot be read straight from a header or the URL. It has a fixed overload, `VaryByValue("edition", "2026")`, and two computed ones taking `HttpContext` (one synchronous, one returning `ValueTask`): ```csharp options.AddPolicy("Localized", b => b .SetVaryByQuery("day") .VaryByValue(ctx => new("culture", CultureInfo.CurrentUICulture.Name))); ``` The function runs when the policy is evaluated, before the endpoint, so whatever it reads (a culture, a tenant id, a feature flag) must already be set at that point in the pipeline. Pairs are sorted by key before they enter the cache key, so their order does not matter. ## Traps - **No `Vary` header is emitted.** The rules shape only the server's key. If browsers or a CDN also cache the response, the endpoint must send its own `Vary` and `Cache-Control` headers. - **Wrong key, wrong user.** Narrowing the key below what the handler reads serves one visitor's variant to another; that is the classic output caching bug. - **Key characters.** If a path, header value or vary value contains the provider's internal delimiter characters, no key is built and the request is simply not cached.

  • Is the default vary-by-every-query-key behaviour a risk in production?
    It can be. Every distinct query string creates an entry, so random or tracking parameters fragment the cache and let a client fill the default 100 MB store with junk until new responses stop being cached. Listing only the keys the handler actually reads with `SetVaryByQuery` fixes both problems.
  • When would you call SetVaryByHost(false)?
    When the same app answers on several host names (for example a bare domain and a www alias) and the response does not depend on which one was used. By default the host is part of the key, so each alias keeps its own copy; turning it off lets them share entries.

  • By default only the path is in the key, so query strings are ignored.
  • SetVaryByQuery adds keys on top of the default * wildcard.
  • Output caching sends a Vary header so browsers cache each variant correctly.
  • [OutputCache] has a VaryByValue property for computed key parts.
  • Listing fewer query keys is always safe because it only improves hit rate.