skip to content

What must a request and its response satisfy for ASP.NET Core's response caching middleware to store and later serve them, and which of those checks can surprise you?

level: middleimportance: should knowfreq 32%

answer

  1. GET or HEAD, no Authorization header
  2. response must say public
  3. no Set-Cookie, no Vary: *
  4. status 200 and still fresh
  5. cookie auth is not checked

basics

~20 s

The request must be a GET or HEAD without an Authorization header; the response must be a fresh 200 marked Cache-Control: public, without private, no-store, no-cache, Set-Cookie or Vary: *. Request no-cache or no-store directives skip lookup or storage.

solid answer

~40 s

On the request side the middleware only considers `GET` and `HEAD` without an `Authorization` header; a request `Cache-Control: no-cache` (or `Pragma: no-cache` when no `Cache-Control` is present) skips lookup, and `no-store` skips storage. On the response side it stores only a 200 whose `Cache-Control` contains `public` and none of `private`, `no-store` or `no-cache`, with no `Set-Cookie`, a `Vary` other than `*`, a lifetime that has not already run out, and a body within `MaximumBodySize` (64 MB). Serving checks freshness against the entry's `max-age` or `s-maxage` and the request's `max-age`, `min-fresh` and `max-stale`; `only-if-cached` on a miss gets 504. The surprises: authentication is judged only by the `Authorization` header, so a cookie-authenticated request whose action is marked `public` is stored and replayed to others; and the key ignores the query string unless `VaryByQueryKeys` is set.

code

http · 7 lines
http
GET /api/timetable?route=12 HTTP/1.1
Host: transit.example
Cache-Control: max-age=0

HTTP/1.1 200 OK
Cache-Control: public,max-age=300
Content-Type: application/json; charset=utf-8

go deeper

for a junior

Remember the basics: anonymous GET or HEAD, status 200, response marked public, no Set-Cookie. A browser refresh usually bypasses the cache.

for a middle

Separate request checks (method, Authorization header, no-cache, no-store) from response checks (public, private, no-store, no-cache, Set-Cookie, Vary *, 200, freshness).

for a senior

Explain the two production traps: cookie-authenticated responses marked public get shared, and the key ignores the query string unless VaryByQueryKeys is set.

for a principal

Judge whether a header-driven server cache is safe for a given API at all, given that a single public attribute on a per-user action leaks data.

## How the middleware decides ASP.NET Core's `ResponseCachingMiddleware` delegates every decision to an internal policy provider that asks four questions per request. Knowing them explains nearly every "it is not caching" or "it cached the wrong thing" report. 1. **May this request use caching at all?** 2. **May it be served from storage?** 3. **May its response be stored?** 4. **Is the produced response cacheable?** ## Request-side checks | Check | Effect when it fails | |---|---| | method is `GET` or `HEAD` | no lookup, no storage | | no `Authorization` header | no lookup, no storage | | request `Cache-Control` lacks `no-cache` (or, without `Cache-Control`, `Pragma` lacks `no-cache`) | no lookup; the endpoint runs | | request `Cache-Control` lacks `no-store` | the new response is not stored | When serving, the middleware also applies the request's freshness requirements: a request `max-age` lower than the stored one shortens it (so `max-age=0` always misses), `min-fresh` adds to the entry's age, and `max-stale` with a value lets a slightly stale entry through, unless the stored response says `must-revalidate` or `proxy-revalidate`. A request with `only-if-cached` and no usable entry gets **504 Gateway Timeout**. ## Response-side checks After the endpoint runs, the response is stored only if **all** of these hold: - `Cache-Control` contains **`public`**; - it contains none of **`no-store`**, **`no-cache`** or **`private`**; - there is **no `Set-Cookie`** header; - `Vary` is not exactly `*`; - the status is **200 OK**; - the response is not already expired by its `s-maxage`, `max-age` or `Expires`; - the body fits `ResponseCachingOptions.MaximumBodySize` (64 MB) and the in-memory store's `SizeLimit` (100 MB) has room. The lifetime is taken from `s-maxage`, then `max-age`, then `Expires`. ## The surprises ### Cookie authentication is invisible to it The only identity check is the **`Authorization` header**. A request authenticated by a cookie has no such header, so if the action is marked `public` (for instance `[ResponseCache(Duration = 60)]`, whose default `Location` is `Any`), the middleware stores that user's response and replays it to the next visitor of the same URL. Per-user endpoints must say `Location = ResponseCacheLocation.Client` (private) or `NoStore = true`; the middleware will then refuse them. ### The query string is not in the key The middleware's base key is method, scheme, host and path. Two requests that differ only in their query string share one entry unless `VaryByQueryKeys` is set through `[ResponseCache]` or `IResponseCachingFeature`. For a bus timetable API addressed as `/api/timetable?route=12`, that is a correctness bug, not a tuning detail. ### Cookies anywhere in the pipeline block storage Any component that adds `Set-Cookie` (cookie-based TempData, a session cookie, a sliding authentication cookie being renewed) makes the response uncacheable for that request, so hit rates can look random. ### Testing with a browser Browsers send `no-cache` or `max-age=0` on reload, so caching appears not to work. Test with a tool that lets you control request headers, or turn on `Debug` logging for `Microsoft.AspNetCore.ResponseCaching`, whose messages name the reason for each refusal. ## Reading the refusals The middleware logs one event per failed check, which turns guesswork into a lookup: | Event name | Meaning | |---|---| | `RequestWithAuthorizationNotCacheable` | the request carried an `Authorization` header | | `RequestWithNoCacheNotCacheable` | the request said `Cache-Control: no-cache` | | `RequestWithPragmaNoCacheNotCacheable` | the request said `Pragma: no-cache` without `Cache-Control` | | `ResponseWithoutPublicNotCacheable` | the response lacked `public` | | `ResponseWithNoCacheNotCacheable` | the response said `no-cache` | | `ResponseWithSetCookieNotCacheable` | the response set a cookie | All of these are logged at `Debug` level, so they are invisible with the default `Information` filter. ## Practical checklist for the timetable API 1. Anonymous `GET` endpoints only. 2. `[ResponseCache(Duration = 300, VaryByQueryKeys = new[] { "route", "day" })]` on the action. 3. `app.UseResponseCaching()` registered, and nothing in the pipeline setting cookies on those responses. 4. Per-user endpoints marked `Location = ResponseCacheLocation.Client` or `NoStore = true`.

  • Why would a Razor page that renders a form never be stored by the response caching middleware?
    Generating an antiforgery token makes the antiforgery system overwrite `Cache-Control` with `no-cache, no-store` and set `Pragma: no-cache`, and it may also issue the antiforgery cookie with `Set-Cookie`. Either one fails the middleware's response checks, so pages with forms are deliberately uncacheable.
  • How long does the middleware keep a response marked public,max-age=300,s-maxage=60?
    Sixty seconds. When computing an entry's lifetime the middleware takes `s-maxage` first, then `max-age`, then `Expires`, because it acts as a shared cache. Browsers would still keep their private copies for 300 seconds.

  • The response caching middleware never caches requests from signed-in users.
  • A response without Cache-Control: public is stored for a short default time.
  • Request Cache-Control headers are ignored; only the response decides.
  • 404 and 301 responses are cached so repeated misses stay cheap.
  • Responses that set cookies are cached with the cookie header removed.