skip to content

In ASP.NET Core output caching, which requests and responses does the default policy refuse to cache, and how long does it keep the rest?

level: middleimportance: must knowfreq 48%

answer

  1. GET or HEAD only
  2. Authorization header skips the lookup
  3. Set-Cookie blocks storage
  4. only status 200 is stored
  5. DefaultExpirationTimeSpan = 60 seconds

basics

~10 s

The default policy caches only anonymous GET or HEAD requests whose response is a 200 with no Set-Cookie header, varies by every query-string key, and keeps each entry 60 seconds (OutputCacheOptions.DefaultExpirationTimeSpan).

solid answer

~40 s

The default policy, which `.CacheOutput()`, `[OutputCache]` and builder-made policies start from, checks the request first: a method other than `GET` or `HEAD`, an `Authorization` header, or an already authenticated `HttpContext.User` means no cache lookup and no storage. After the endpoint runs it checks the response: a `Set-Cookie` header, an authenticated user, or any status other than 200 means the response is not stored, so 404s, redirects and 204s are recomputed every time. It varies the key by every query-string key and value, and an entry lives 60 seconds unless a policy calls `Expire` or you change `OutputCacheOptions.DefaultExpirationTimeSpan`. Bodies larger than `MaximumBodySize` (64 MB) are not stored either. A client cannot opt out with `Cache-Control: no-cache`: of the request's `Cache-Control` directives the middleware honours only `only-if-cached`, answering 504 on a miss.

code

csharp · 23 lines
csharp
public sealed class SignedInPolicy : IOutputCachePolicy
{
    public ValueTask CacheRequestAsync(OutputCacheContext ctx, CancellationToken ct)
    {
        ctx.EnableOutputCaching = true;
        ctx.AllowCacheLookup = true;
        ctx.AllowCacheStorage = true;
        ctx.AllowLocking = true;
        ctx.CacheVaryByRules.VaryByValues["user"] =
            ctx.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "anon";
        return ValueTask.CompletedTask;
    }

    public ValueTask ServeFromCacheAsync(OutputCacheContext ctx, CancellationToken ct) => ValueTask.CompletedTask;

    public ValueTask ServeResponseAsync(OutputCacheContext ctx, CancellationToken ct)
    {
        var res = ctx.HttpContext.Response;
        if (res.StatusCode != StatusCodes.Status200OK || res.Headers.SetCookie.Count > 0)
            ctx.AllowCacheStorage = false;   // keep the default policy's response guards
        return ValueTask.CompletedTask;
    }
}

go deeper

for a junior

Know the short list: anonymous GET or HEAD, status 200, no Set-Cookie, 60-second lifetime. That alone explains most cases where caching seems not to work.

for a middle

Separate the request-side checks (method, credentials) from the response-side ones (cookies, status, size), and explain that the client's Cache-Control cannot bypass a fresh entry.

for a senior

Explain why each refusal protects you, which responses silently become uncacheable (pages issuing cookies), and how a custom IOutputCachePolicy caches personal responses safely with a per-user key part.

for a principal

Weigh relaxing the defaults against the risk of serving one user's data to another; argue for keeping output caching to public representations and caching data instead for personal views.

## Where the default policy comes from ASP.NET Core's output cache is driven by **policies**, objects implementing `IOutputCachePolicy` that set flags on an `OutputCacheContext`. An internal `DefaultPolicy` encodes the safe defaults, and you get it in more places than you might think: - `.CacheOutput()` with no arguments attaches exactly that policy; - `[OutputCache]` builds its policy on top of it; - every policy made with an `OutputCachePolicyBuilder` (`CacheOutput(b => ...)`, `AddPolicy(name, b => ...)`, `AddBasePolicy(b => ...)`) starts from it unless you pass `excludeDefaultPolicy: true`. So in practice the default policy's refusals apply to nearly every output-cached endpoint. Interviewers ask about them because they explain most "the cache does nothing" reports. ## Request-side checks Before the endpoint runs, the policy decides whether this request may be looked up and stored at all: 1. **Method.** Only `GET` and `HEAD` qualify. A `POST`, `PUT` or `DELETE` is never served from the cache. 2. **Credentials.** A request with any `Authorization` header, or whose `User.Identity.IsAuthenticated` is already `true`, gets neither lookup nor storage. 3. **Vary rule.** It sets the query-string rule to `*`, so every distinct query string gets its own entry. 4. **Locking.** It turns on request coalescing for concurrent misses. ## Response-side checks After the endpoint has produced its response, the policy can still veto storage: | Response condition | Effect | |---|---| | a `Set-Cookie` header is present | not stored | | the user is now authenticated | not stored | | status is anything but `200 OK` | not stored | | body larger than `MaximumBodySize` (64 MB) | buffering stops, not stored | | `Content-Length` does not match the bytes written | not stored | The cookie rule matters more than it looks: a page that issues a session or antiforgery cookie on its response is silently uncacheable. The status rule means a 404 for a missing festival act is recomputed on every request; if that is expensive, rate limiting or a data cache is the tool, not the output cache. ## Why each refusal exists Each check closes a way a shared cache could hurt you: - **Unsafe methods** change state; replaying a stored `POST` result would skip the change. - **Credentials** mean the response may be personal. Storing it under a key built from the URL would hand one user's page to the next visitor. - **`Set-Cookie`** would be replayed with the stored headers, giving every later visitor the first visitor's cookie, session id included. - **Non-200 statuses** are often transient (a 503 during a deploy, a 404 before content is published); caching them would freeze an error in place. `GET` and `HEAD` get separate entries, because the method is part of the key. ## Lifetime and capacity - An entry is valid for `OutputCacheOptions.DefaultExpirationTimeSpan`, **60 seconds**, unless a policy calls `Expire(...)` or the attribute sets `Duration` (in seconds). - The default in-memory store is bounded by `SizeLimit`, **100 MB**; once full, new responses are not cached until older entries leave. - Paths are compared case-insensitively unless `UseCaseSensitivePaths` is `true`. ## What the client can and cannot change The output cache is configured on the server, and clients do not override it: - `Cache-Control: no-cache` or `max-age=0` on the request (which browsers send on a reload) **does not** bypass a fresh entry. - `Cache-Control: only-if-cached` on a miss gets **504 Gateway Timeout**. - `If-None-Match` matching the stored `ETag`, or a satisfied `If-Modified-Since`, gets **304 Not Modified** with the stored validator headers. ## Caching what the default refuses To cache, say, an authenticated dashboard fragment, you write your own `IOutputCachePolicy`: in `CacheRequestAsync` set `EnableOutputCaching`, `AllowCacheLookup` and `AllowCacheStorage` to `true`, and add a per-user part to the key (for example an entry in `CacheVaryByRules.VaryByValues`) so one user's response is never replayed to another. Passing `excludeDefaultPolicy: true` and calling `Cache()` is **not** enough: that only sets `EnableOutputCaching`, leaving lookup and storage off, so nothing is cached. Remember too that the key never includes the request body, which is why caching `POST` responses is rarely correct.

  • Why does the default policy check the Authorization header and not only the authenticated user?
    The request-side check runs before the endpoint, and a request carrying credentials is personal even if `HttpContext.User` has not been populated yet. Refusing on the raw `Authorization` header means a bearer-token caller is never served a shared entry and its response is never stored for others.
  • Would you cache a POST search endpoint with the output cache?
    Rarely. The default policy refuses `POST`, and a custom policy that allows it still builds the key from method, host, path, query and vary values, never the body. Two searches with different bodies would share one entry unless you compute a key part from the criteria yourself, so a data cache behind the handler is usually the better tool.

  • The default output cache policy caches POST responses whose bodies are identical.
  • 404 responses are cached by default so missing pages stay cheap.
  • A browser's Cache-Control: no-cache makes the output cache skip its stored entry.
  • Output cache entries live until memory runs out unless you set Duration.
  • excludeDefaultPolicy: true plus Cache() is enough to cache authenticated requests.