skip to content

Response Cache Middleware

The response caching middleware stores responses only when Cache-Control allows it, and [ResponseCache] writes those headers for browsers and CDNs. Interviewers ask why output caching replaced it.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In an ASP.NET Core MVC controller, what headers does [ResponseCache(Duration = 300)] write, and does it cache anything on the server by itself?

level: juniorimportance: must knowfreq 50%

answer

  1. an MVC filter, not a cache
  2. Location defaults to Any
  3. public,max-age=300
  4. Client = private, None = no-cache
  5. no Duration: InvalidOperationException

basics

~20 s

[ResponseCache(Duration = 300)] writes Cache-Control: public,max-age=300 (Location defaults to Any) and nothing else; it caches nothing on the server. Browsers and shared caches act on that header; a server cache needs UseResponseCaching or output caching.

solid answer

~40 s

`[ResponseCache]` is an MVC filter for controllers and Razor Pages page models. Before the action runs it removes any existing `Cache-Control`, `Pragma` and `Vary` headers and writes new ones from its properties: `Duration` becomes `max-age`, `Location` picks the directive (`Any` gives `public`, the default; `Client` gives `private`; `None` gives `no-cache`), `NoStore = true` writes `no-store`, and `VaryByHeader` writes a `Vary` header. So `[ResponseCache(Duration = 300)]` yields `Cache-Control: public,max-age=300`. It stores nothing itself: browsers, proxies and CDNs decide what to keep, and a server-side copy exists only if the app also runs the response caching middleware. If neither `Duration`, `NoStore = true` nor `Location = None` is set, the filter throws `InvalidOperationException`. It has no effect on Minimal API endpoints, which never run MVC filters.

code

csharp · 11 lines
csharp
[HttpGet("{route}")]
[ResponseCache(Duration = 300)]                    // Cache-Control: public,max-age=300
public Task<Timetable?> Get(string route) => store.FindAsync(route);

[HttpGet("{route}/live")]
[ResponseCache(Duration = 15, Location = ResponseCacheLocation.Client)]
public Task<LivePositions> Live(string route) => tracker.GetAsync(route);  // private,max-age=15

[HttpGet("/error")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public IActionResult Error() => Problem();          // no-store,no-cache + Pragma: no-cache

go deeper

for a junior

Recall that [ResponseCache] only writes headers: Duration becomes max-age and the default Location Any becomes public. Nothing is cached on the server by the attribute alone.

for a middle

Map each property to its header (Client to private, None to no-cache, NoStore to no-store, VaryByHeader to Vary) and explain why a missing Duration throws.

for a senior

Point out that the filter runs before the action, so error responses inherit the headers, and that Minimal APIs and output caching ignore the attribute entirely.

for a principal

Decide which endpoints may be cached by browsers and CDNs at all, and own the header policy centrally (cache profiles, conventions) instead of per-action guesses.

## What the attribute is `ResponseCacheAttribute` lives in `Microsoft.AspNetCore.Mvc`. Despite the name, it is a **header writer**: an `IFilterFactory` that creates an action filter (and, for Razor Pages, a page filter) whose only job is to set HTTP caching headers on the response. It does not store responses anywhere. Interviewers ask about it because candidates often believe it is a server cache. ## Which headers it writes The filter first **removes** `Vary`, `Cache-Control` and `Pragma`, then writes: | Attribute settings | Headers written | |---|---| | `Duration = 300` (Location defaults to `Any`) | `Cache-Control: public,max-age=300` | | `Duration = 300, Location = ResponseCacheLocation.Client` | `Cache-Control: private,max-age=300` | | `Location = ResponseCacheLocation.None` (no Duration) | `Cache-Control: no-cache`, `Pragma: no-cache` | | `Duration = 300, Location = ResponseCacheLocation.None` | `Cache-Control: no-cache,max-age=300` | | `NoStore = true` | `Cache-Control: no-store` | | `NoStore = true, Location = ResponseCacheLocation.None` | `Cache-Control: no-store,no-cache`, `Pragma: no-cache` | | `VaryByHeader = "Accept-Language"` | adds `Vary: Accept-Language` | Two rules follow from the source: 1. **`Duration` is mandatory** unless `NoStore` is `true` or `Location` is `None`. `[ResponseCache(Location = ResponseCacheLocation.Any)]` alone throws `InvalidOperationException` ("If the 'NoStore' property is not set to true, 'Duration' property must be specified.") the first time the action runs. 2. **`NoStore` overrides the rest**: with it set, `Duration` and `Location = Any` or `Client` are ignored. ## A read-only timetable API A city bus network publishes timetables that change once a day. Letting browsers and the city's CDN keep them for five minutes takes one attribute: ```csharp [ApiController] [Route("api/timetable")] public class TimetableController(TimetableStore store) : ControllerBase { [HttpGet("{route}")] [ResponseCache(Duration = 300)] public async Task<ActionResult<Timetable>> Get(string route) => await store.FindAsync(route) is { } t ? t : NotFound(); } ``` Every response from that action now carries `Cache-Control: public,max-age=300`, so a rider's phone reuses it for five minutes and the CDN can answer other riders without reaching the app. What those directives mean to each cache is HTTP's business; what matters here is that ASP.NET Core only *declares* them. ## Choosing Location across the API The bus network's API has three kinds of endpoint, and each maps to one setting: - **Shared, read-only data** (timetables, stop lists): `Duration` with the default `Location = Any`, so phones and the CDN may both keep a copy. - **Per-rider data** (saved favourites, recent journeys): `Location = ResponseCacheLocation.Client`, which writes `private`, so only the rider's own browser may keep it. - **Must never be reused** (ticket purchase confirmations, account pages): `NoStore = true`, usually with `Location = ResponseCacheLocation.None`, so the filter writes `no-store,no-cache` and `Pragma: no-cache`. Applying the attribute at controller level sets a default for every action in it; an action-level attribute then replaces the controller's settings for that action rather than merging with them. Razor Pages accept it on the page model class but not on individual handler methods. ## When the headers are written The filter runs in `OnActionExecuting`, **before** the action body. Consequences: - code inside the action that sets `Response.Headers.CacheControl` runs later and wins; - the headers stay even if the action then returns `NotFound()` or another error result, so those responses carry the same `Cache-Control` unless something changes them (which is why `NoStore = true` on error pages is common); - a method-level `[ResponseCache]` replaces a class-level one entirely rather than merging with it. ## What it does not do - **No server cache.** Without `AddResponseCaching()` and `UseResponseCaching()`, nothing is stored on the server. With them, the middleware reads these headers and decides for itself. - **No output caching.** The output cache middleware ignores this attribute; it uses `[OutputCache]` and `CacheOutput()`. - **No Minimal APIs.** It is an MVC filter, so `app.MapGet(...)` handlers never run it; there you set headers yourself, for example through `context.Response.GetTypedHeaders().CacheControl`. - **No query-string vary for HTTP caches.** `VaryByQueryKeys` has no header equivalent; it only instructs the response caching middleware, and throws if that middleware is absent.

  • How do you send the same header from a Minimal API endpoint?
    Set it yourself, because MVC filters never run there: `ctx.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromMinutes(5) };`, or write `ctx.Response.Headers.CacheControl` directly, inside the handler or an endpoint filter. The response caching middleware, if used, reads the header the same way.
  • Why might a 404 from this action still carry Cache-Control: public,max-age=300?
    The filter writes headers in `OnActionExecuting`, before the action decides its result, so a `NotFound()` keeps them unless something removes them. A CDN may then cache the 404 for five minutes. Override the header on that path or keep missing routes out of shared caches deliberately.

  • [ResponseCache] stores the response in server memory for Duration seconds.
  • Location defaults to Client, so responses are private unless you say otherwise.
  • Duration can be omitted; the attribute then falls back to a 60-second default.
  • Putting [ResponseCache] on a Minimal API lambda sets the Cache-Control header.
  • [ResponseCache] enables output caching for the action it decorates.
open as a page

How does ASP.NET Core's response caching middleware (UseResponseCaching) differ from output caching, and why is output caching usually the better server-side cache today?

level: middleimportance: must knowfreq 45%

basics

~20 s

The response caching middleware stores only what the response's Cache-Control headers allow and lets request headers bypass it; output caching (ASP.NET Core 7+) follows server-side policies, ignores client no-cache, supports pluggable stores, tag eviction and request locking.

open as a page

In ASP.NET Core MVC, how do CacheProfiles work with [ResponseCache(CacheProfileName = ...)], and which value wins when the attribute and profile disagree?

level: middleimportance: should knowfreq 24%

basics

~10 s

CacheProfiles is a named dictionary of CacheProfile settings on MvcOptions; [ResponseCache(CacheProfileName = "x")] uses it as defaults, and any property set on the attribute overrides the profile's. An unknown profile name throws InvalidOperationException.

open as a page

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%

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.

open as a page

A bus timetable API behind ASP.NET Core's response caching middleware returns route 12's timetable for route 31; why, and how does VaryByQueryKeys fix it?

level: seniorimportance: should knowfreq 26%

basics

~20 s

The middleware's key is method, scheme, host and path only, so /api/timetable?route=12 and ?route=31 share one entry. VaryByQueryKeys = new[] { "route" } adds that query key to the key; it requires UseResponseCaching, or the filter throws.

open as a page