Cache-Control is an HTTP response header that tells clients and intermediate proxies how a response may be cached. In a board-game API, it lets each endpoint declare whether its response can be reused. ASP.NET Core’s [ResponseCache] attribute sets these directives without requiring you to write the header yourself. section 3.1.3 section 8.2
Choose a directive for each response:
- For a cacheable board-game GET response, [ResponseCache(Location = ResponseCacheLocation.Any, Duration = 60)] produces a public response with a 60-second max-age. section 8.2 section 8.2.2
- For a response that must not be stored, use [ResponseCache(NoStore = true)]. The API’s error endpoints use this setting. section 3.1.3 section 8.2
- Scope and duration can differ by API version: the board-game GET exercise calls for private with a 120-second max-age in v2, and no-store in v1. section 3.4.2
You can also write the header through HttpContext.Response.Headers. A Minimal API endpoint can set "cache-control" to "no-cache, no-store", but repeating directives this way is harder to maintain. Prefer [ResponseCache] unless its settings do not meet a specific need. section 8.2.1
Listing 8.1 Program.cs file: /cache/test/1 endpoint using Minimal API
app.MapGet("/cache/test/1",
[EnableCors("AnyOrigin")]
(HttpContext context) =>
{
context.Response.Headers["cache-control"] =#1
"no-cache, no-store";#1
return Results.Ok();
});
The Minimal API example shows where a response header can be set directly before returning a result. section 8.2.1
A missing [ResponseCache] attribute can leave a response with no Cache-Control header. Clients and proxies may then choose whether to cache it, which is risky if it contains sensitive information. A fallback middleware can set "no-cache, no-store" for such responses while allowing an explicit [ResponseCache] setting to override the default. section 8.2.2
Check the fallback
Run an endpoint without [ResponseCache], open the browser’s Developer Tools Network tab, and inspect its response headers. Before adding fallback middleware, the example endpoint has no Cache-Control header; the middleware supplies a default directive. section 8.2.2
