Output Caching in ASP.NET Core: Tags, Eviction and the Traps

Cache whole pages on the server, clear them the moment content changes, and avoid the antiforgery and nonce traps that break cached HTML.

R M Shahidul Islam Shahed · 4 min read

Output caching stores a whole response on the server and serves it again without running your controller, your queries or your views. For a content site it is the single biggest performance win available: a cached page costs almost nothing to serve. This guide sets it up on .NET 10, clears it exactly when content changes, and covers the traps that break cached HTML in production.

Output caching vs response caching

ASP.NET Core has two features with similar names:

Response caching Output caching
Where it lives Browsers and proxies, via Cache-Control Your server's memory (or Redis)
Can you clear it on demand No Yes, by tag
Respects authenticated users Depends on headers Skips them by default

Response caching asks other machines to keep a copy. Output caching keeps the copy yourself, which means you can throw it away the moment a post is edited. For content that changes on publish, that control is what you want.

Turn it on

Register the service with a named policy, then add the middleware after authentication so it knows who is signed in.

csharp
builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("public", policy => policy
        .Expire(TimeSpan.FromHours(24))   // safety net, not the normal way out
        .Tag("posts")
        .SetVaryByQuery("*"));            // ?page=2 and ?topic=ef-core are separate entries
});

var app = builder.Build();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseOutputCache();

Apply the policy where it belongs. A base class for public controllers keeps it in one place:

csharp
[OutputCache(PolicyName = "public")]
public abstract class PublicControllerBase : Controller;

[OutputCache(NoStore = true)]          // one entry per search term is a waste of memory
public sealed class SearchController : PublicControllerBase { /* … */ }

Know what the default rules already do

The built-in policy is conservative, and that is good news. It only stores:

  • GET and HEAD requests
  • responses with status 200
  • requests from anonymous users
  • responses that don't set a cookie

So admins and previews are never cached, and a page that accidentally sets a cookie isn't stored. That last rule is also why your cache can look like it "does nothing": if every response sets a cookie, nothing is ever cached.

Clear by tag when content changes

The 24-hour expiry is a safety net. The real way entries leave the cache is eviction by tag, at the moment the content changes.

csharp
public interface IPublicCache
{
    Task EvictPostsAsync(CancellationToken ct);
}

public sealed class PublicCache(IOutputCacheStore store) : IPublicCache
{
    public Task EvictPostsAsync(CancellationToken ct) =>
        store.EvictByTagAsync("posts", ct).AsTask();
}

Call it from every write that readers can see: publish, unpublish, edits to a published post, deletes, approved comments, topic renames, and the background job that publishes scheduled posts.

csharp
await db.SaveChangesAsync(ct);
if (wasPublic || post.Status == PostStatus.Published)
{
    await cache.EvictPostsAsync(ct);
}

One tag for the whole public site sounds blunt, but it's honest: a new post changes the home page, its topic page, the archive, the sitemap and the feed. Fine-grained tags are hard to get right; one tag is hard to get wrong.

Trap 1: antiforgery tokens in cached HTML

An antiforgery token is tied to the visitor's cookie. Render one into a cached page and every later visitor gets a stranger's token, so their form posts fail. And because issuing the token sets a cookie, the page may not be cached at all.

The fix: cached pages render no token. Forms ask for one when they need it.

csharp
[OutputCache(NoStore = true)]
public sealed class AntiforgeryController(IAntiforgery antiforgery) : PublicControllerBase
{
    [HttpGet("/antiforgery/token")]
    public IActionResult Token() =>
        Json(new { token = antiforgery.GetAndStoreTokens(HttpContext).RequestToken });
}
html
<form method="post" action="/subscribe" asp-antiforgery="false">

The browser fetches /antiforgery/token once, before the first POST, and sends it as a header. The cached HTML stays the same for everyone.

Trap 2: CSP nonces in cached HTML

A Content Security Policy nonce must be new on every response. A cached page carries the nonce from the response that was cached, while the header carries a new one, so the browser blocks your inline script.

Use a hash instead. For a small inline script that never changes, compute its SHA-256 once and put it in the policy:

csharp
public static readonly string CspHash =
    "'sha256-" + Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(ThemeScript.Source))) + "'";

The same cached page is then valid under every response's policy.

Trap 3: varying on the wrong things

SetVaryByQuery("*") makes every distinct query string its own entry. That is right for ?page= and ?topic=, but tracking parameters such as ?utm_source= multiply your entries for no benefit. If your traffic carries them, list the keys you need instead:

csharp
policy.SetVaryByQuery("page", "topic");

Check it works

Request a public page twice while signed out and watch your logs: the second request should not reach your controller. Then publish a post and confirm the home page shows it straight away. If it doesn't, a write path is missing its eviction call.

Wrapping up

Output caching turns a database-backed site into one that serves most pages from memory. Cache anonymous GETs behind one tag, evict that tag on every visible change, and keep per-visitor values (antiforgery tokens, nonces) out of the cached HTML. With those three rules the cache stays fast and never shows stale content.

Keep reading

All articles →
ASP.NET Core & Web APIs

Rate Limiting in ASP.NET Core: Protect Your API Without a Gateway

Fixed window, sliding window, token bucket and concurrency limiters with the built-in middleware, partitioned per client, with friendly 429s.

3 min read
ASP.NET Core & Web APIs

Minimal APIs vs Controllers in 2026: Which Should You Pick?

A practical comparison for real projects: organisation, filters, validation, OpenAPI and testing.

1 min read
Architecture & Production .NET

Background Jobs in ASP.NET Core with BackgroundService and PeriodicTimer

Run scheduled work inside your ASP.NET Core app: BackgroundService, PeriodicTimer, scoped DbContext, safe reruns, and when to reach for Hangfire.

4 min read