Output caching
Output caching stores a whole response and serves it again without running the action. This lesson shows the output caching middleware added in .NET 7, policies with expiry and vary-by rules, tag-based invalidation, and what must never be cached.
- StartFirst requestAction runs; response stored with tag products
- Step 2Next requestsServed from the cache, no action, no database
- Step 3Admin edits a productEvictByTagAsync("products")
- EndNext requestAction runs again and refreshes the cache
What it does
The first request runs the action and stores the response. Later requests for the same URL are served from the cache in microseconds until it expires. For pages that many people see and that change rarely, such as a product catalogue or a home page, this removes most of the load.
Unlike browser caching, the server controls it and can remove entries the moment data changes.
Setting it up
builder.Services.AddOutputCache(o =>
{
o.AddBasePolicy(b => b.Expire(TimeSpan.FromSeconds(30)));
o.AddPolicy("Catalogue", b => b
.Expire(TimeSpan.FromMinutes(10))
.SetVaryByQuery("page", "sort", "search")
.Tag("products"));
});
var app = builder.Build();
app.UseOutputCache(); // after UseRouting and authentication if you use themUsing it
Opt in per action with the attribute, and clear the cache by tag when data changes.
public class ProductsController(ShopContext db, IOutputCacheStore cache) : Controller
{
[OutputCache(PolicyName = "Catalogue")]
public async Task<IActionResult> Index([FromQuery] ProductQuery q) { /* ... */ return View(); }
[HttpPost, ValidateAntiForgeryToken, Authorize(Roles = "Admin")]
public async Task<IActionResult> Edit(ProductEditModel input, CancellationToken ct)
{
// ... save changes ...
await cache.EvictByTagAsync("products", ct); // next request rebuilds the page
return RedirectToAction(nameof(Index));
}
}What not to cache
- Pages that differ per user, such as a cart or account page. By default responses to authenticated requests or with Set-Cookie are not cached; keep it that way.
- Forms with anti-forgery tokens, which are per user.
- POST responses (only GET and HEAD are cached).
- With several servers, the default in-memory store is per server; use the Redis store (AddStackExchangeRedisOutputCache) to share it.
Interview question
How does output caching differ from response caching in ASP.NET Core?
Response caching mainly sets HTTP cache headers so browsers and proxies can cache, and the server follows those headers. Output caching, added in .NET 7, is controlled entirely by the server: it stores responses in a server-side store, supports policies, vary-by rules, resource locking against stampedes and tag-based eviction, regardless of what the client asks.
Want the full details? Read the official Microsoft documentation for this topic.