.NETMedium
What is Output Caching in ASP.NET Core 8+?
Output caching stores the entire response (headers + body) keyed on request features, served from memory or a distributed store. Cheaper than re-running the handler.
builder.Services.AddOutputCache(options => {
options.AddPolicy("ProductList", b => b
.Expire(TimeSpan.FromSeconds(60))
.SetVaryByQuery("category", "page"));
});
app.UseOutputCache();
app.MapGet("/api/products", async (IProductService svc, string? category, int page = 1) =>
Results.Ok(await svc.ListAsync(category, page)))
.CacheOutput("ProductList");
Tag-based invalidation is the killer feature:
options.AddPolicy("Product", b => b.Tag("product-list"));
// In your admin write path:
public async Task PublishAsync(IOutputCacheStore cache) {
await db.SaveChangesAsync();
await cache.EvictByTagAsync("product-list", default);
}
Publishing a new product evicts every cached response tagged product-list.
Different from response caching: response caching emits Cache-Control headers and relies on the client to cache. Output caching stores the response on the server — works regardless of client headers and lets you invalidate.
Don't cache: authenticated personalised content (key by user → cache explosion), POST results, anything with Set-Cookie you need to refresh.