Response caching
Response caching lets browsers, proxies or the server reuse a whole HTTP response instead of running your action again. This lesson explains Cache-Control headers, the [ResponseCache] attribute and server-side output caching.
- StartFirst requestThe action runs and builds the page
- Step 2Response is marked cacheableCache-Control: public, max-age=60
- Step 3A copy is storedBy the browser, a proxy, or the server's output cache
- Step 4Requests within 60 sServed from the cache; your action does not run
- EndAfter 60 sThe next request runs the action again and refreshes the copy
The idea in plain words
Some pages are the same for everyone for a while: a product list, a public article, an API result. HTTP has built-in rules for caching such responses, controlled by the Cache-Control header. When you mark a response as cacheable, browsers and proxies can reuse it without asking your server.
The [ResponseCache] attribute sets those headers for you. If you also want the server itself to keep the rendered response, use output caching, which stores responses in your app and serves them without running the action.
Example: response caching headers
public class ArticlesController : Controller
{
// Cache-Control: public,max-age=60
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any)]
public IActionResult Index() => View(_articles.Latest());
// Never cache pages with personal or sensitive data
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public IActionResult Account() => View();
}Example: server-side output caching
Output caching is configured on the server and can vary the cached copy by query string values.
// Program.cs
builder.Services.AddOutputCache();
var app = builder.Build();
app.UseRouting();
app.UseOutputCache();
// Controller
[OutputCache(Duration = 60, VaryByQueryKeys = new[] { "page" })]
public IActionResult Index(int page = 1) => View(_articles.Page(page));Common mistakes
- Caching pages that contain user-specific data with Location.Any, so a proxy can show one user's page to another.
- Forgetting to vary by query string, so every page number returns page 1.
- Expecting [ResponseCache] alone to cache on the server; it only sets headers unless caching middleware is added.
Interview question
What is the difference between response caching and output caching in ASP.NET Core?
Response caching is driven by HTTP Cache-Control headers: [ResponseCache] sets them and clients or proxies decide whether to reuse responses, with optional middleware honoring the same headers on the server. Output caching, added in .NET 7, is configured by the app and stores responses on the server regardless of client headers, with policies such as varying by query keys and the ability to evict entries by tag.
Want the full details? Read the official Microsoft documentation for this topic.