In an ASP.NET Core MVC controller, what headers does [ResponseCache(Duration = 300)] write, and does it cache anything on the server by itself?
answer
- an MVC filter, not a cache
- Location defaults to Any
- public,max-age=300
- Client = private, None = no-cache
- 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[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-cachego deeper
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.
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.
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.
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.