
ASP.NET Core output caching does not cache an endpoint result, an EF Core query or a domain object. It caches a completed HTTP response: status, headers and body bytes.
On a hit, the endpoint does not run. Model binding, dependency calls, allocation and serialization are skipped. That is why output caching can be so effective and why one missing key dimension can return the wrong user’s data with impressive speed.
The correctness rule is strict:
Every request that maps to one cache key must be allowed to receive exactly the same response status, headers and body bytes.
Everything else in this article follows from that statement.
Release status: The .NET 11 details reflect Preview 7 from August 2026.
IOutputCachePolicyProvideris new in .NET 11; the core output-cache behavior is stable in earlier supported ASP.NET Core versions.
Caching is opt-in
Registration only makes the middleware available:
1WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
2
3builder.Services.AddOutputCache();
4
5WebApplication app = builder.Build();
6
7app.UseOutputCache();An endpoint chooses the default or a named policy:
1app.MapGet("/api/catalog", CatalogEndpoints.GetAsync)
2 .CacheOutput();1[HttpGet]
2[OutputCache]
3public async Task<ActionResult<CatalogPage>> GetAsync(
4 CancellationToken cancellationToken)
5{
6 CatalogPage page = await LoadCatalogAsync(cancellationToken);
7 return Ok(page);
8}Opt-in is preferable because a successful GET is not automatically public, stable, bounded or side-effect free.
What one entry contains
An output-cache entry stores:
- creation time;
- HTTP status code;
- response headers, except framework-managed exclusions; and
- the final response body as bytes.
The creation time drives freshness and the Age header. Without a policy duration, the default expiration is 60 seconds.
The default policy stores only 200 OK. A custom policy can cache 404, redirects or failures, but that changes semantics. A negative entry can hide a resource created moments later and an error response can replay correlation or dependency details.
Most headers are cached. Content-Length, Age and Request-Id are excluded because the framework recalculates or intentionally avoids replaying them. Custom request IDs, nonces, timestamps, CORS values, ETag, Location and security headers can all become part of the entry depending on middleware order.
The body is the exact serialized byte sequence observed at the cache boundary. Existing entries do not change when serializer settings or application code change. A distributed store can therefore replay output created by an older deployment.
Tags are store metadata for grouped eviction. They do nothing unless a mutation actually calls EvictByTagAsync.
What a hit skips
Output caching does not retain scopes, domain objects, query results, logs, traces, authorization decisions or endpoint side effects. It simply avoids running them again.
A GET that writes an audit event, updates last-access state or issues a one-time token is already difficult to reason about. Caching makes the defect obvious: those effects run on a miss and disappear on a hit.
Middleware order defines the cache boundary
Middleware before output caching executes for hits and misses. Middleware after it is bypassed on a hit.
1request
2 -> middleware before cache: always runs
3 -> output cache
4 -> hit: replay response
5 -> miss: downstream middleware and endpointThis affects authentication, authorization, rate limiting, compression, CORS, correlation and response headers.
A practical public API order is:
1WebApplication app = builder.Build();
2
3app.UseForwardedHeaders();
4app.UseRouting();
5app.UseCors();
6app.UseAuthentication();
7app.UseAuthorization();
8app.UseRateLimiter();
9app.UseResponseCompression();
10app.UseOutputCache();
11
12app.MapEndpoints();This states several decisions:
- trusted scheme and host exist before key generation;
- CORS, authentication and authorization run on every hit;
- rate limits count incoming requests, not only endpoint executions;
- the store keeps uncompressed bodies; and
- endpoint work is bypassed.
Moving rate limiting after the cache makes hits free from that quota. Moving authorization after it can serve data before access control. Neither is a formatting change.
Response compression before output caching compresses as cached bytes are written, so the store can keep one uncompressed representation. Compression after output caching can put compressed bytes in the entry, which requires Accept-Encoding in the key.
Per-request headers belong outside the cached boundary when they must remain unique.
The default safety rules are only a baseline
The default policy stores a response only when:
- the request is
GETorHEAD; - no
Authorizationheader exists; - the principal is anonymous;
- the response is
200; and - the response has no
Set-Cookieheader.
These rules prevent common leaks but cannot know whether an anonymous response varies by language, media type, feature assignment, geography or another header.
Output caching is server-controlled. Client Cache-Control: no-cache does not normally bypass it and a response Cache-Control: no-store does not replace NoCache() in the output-cache policy. HTTP response caching and server output caching are separate layers.
Understand the default key
The base key includes method, scheme, host and port, path base, path and every query parameter.
METHOD | SCHEME | HOST:PORT | PATHBASE | PATH | QUERYHeaders such as Accept, Accept-Language, Origin and custom representation headers are not included automatically.
GET and HEAD use different keys. Paths are case-insensitive by default; UseCaseSensitivePaths must match routing semantics.
Query names are normalized and repeated values are sorted. These requests can share an entry:
1/search?tag=dotnet&tag=azure
2/search?tag=azure&tag=dotnetThat is correct only if repeated-value order has no application meaning.
Varying by every query parameter is conservative but can destroy hit ratio and store capacity when tracking or random values do not affect output. An allowlist and validation of every accepted value provide a bounded key space.
A policy should name every response variant
This policy defines a bounded body size, a five-minute lifetime, explicit query values, language variation, a versioned prefix and an invalidation tag:
1using Microsoft.AspNetCore.OutputCaching;
2using Microsoft.Net.Http.Headers;
3
4public static class OutputCachePolicies
5{
6 public const string Catalog = "catalog-v2";
7 public const string CatalogTag = "catalog";
8}Register the policy in Program.cs:
1using Microsoft.AspNetCore.OutputCaching;
2using Microsoft.Net.Http.Headers;
3
4WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
5
6builder.Services.AddOutputCache((OutputCacheOptions options) =>
7{
8 options.SizeLimit = 128 * 1024 * 1024;
9 options.MaximumBodySize = 1024 * 1024;
10 options.DefaultExpirationTimeSpan = TimeSpan.FromSeconds(30);
11 options.UseCaseSensitivePaths = false;
12
13 options.AddPolicy(
14 OutputCachePolicies.Catalog,
15 (OutputCachePolicyBuilder policy) =>
16 {
17 policy
18 .Expire(TimeSpan.FromMinutes(5))
19 .SetCacheKeyPrefix(OutputCachePolicies.Catalog)
20 .SetVaryByQuery("page", "pageSize", "category")
21 .SetVaryByHeader(HeaderNames.AcceptLanguage)
22 .Tag(OutputCachePolicies.CatalogTag);
23 });
24}); 1app.MapGet(
2 "/api/catalog",
3 async (
4 int page,
5 int pageSize,
6 string? category,
7 CatalogQuery query,
8 CancellationToken cancellationToken) =>
9 {
10 CatalogPage result = await query.ExecuteAsync(
11 page,
12 pageSize,
13 category,
14 cancellationToken);
15
16 return TypedResults.Ok(result);
17 })
18 .CacheOutput(OutputCachePolicies.Catalog);The endpoint still bounds pageSize and validates category values. Cache variation does not limit the number of valid combinations an attacker can create.
The catalog-v2 prefix represents response compatibility. It should change when serialized meaning changes, not on every deployment. Versioning by build number creates a cold cache every time; never versioning can replay incompatible old bytes from Redis.
Canonical values beat raw headers
Accept-Language has many strings that resolve to the same supported culture. Varying by the raw header is safe but fragments entries.
It should be resolved to a bounded value such as en, de or fr and passed through VaryByValue when the same resolver also controls response generation. The same applies to media type, API version and feature profile.
Output bytes can vary by Accept, Accept-Language, Accept-Encoding, version headers or custom representation profiles. Every material choice enters the output key and the HTTP Vary header when intermediary caches are also involved.
Raw bearer tokens, API keys and cookies never become key material. They are secrets, high-cardinality values and poor authorization models.
Authenticated output has the highest risk
The default policy excludes authenticated requests. Overriding that requires more than a user ID. Tenant, subject, entitlement version, locale, feature assignment, representation, route values and permission changes may all affect output.
Authorization middleware placed before output caching still checks endpoint access on every hit and can reject a user removed from a required role. However, finer-grained checks and data filtering inside the skipped endpoint do not rerun. Cached fields can therefore reflect older permissions even while endpoint authorization succeeds. Per-user entries also tend to have low reuse and high cardinality.
Safer options are:
- Cache only shared public output.
- Cache permission-neutral typed data below the endpoint with
HybridCache. - Use a short, explicit authorization-version key with eviction.
- Do not cache the personalized endpoint.
Any authenticated policy gets negative tests with at least two users and two tenants, warming the cache in both request orders.
POST should not use output caching
Custom policies can enable POST, but the default key does not include the body. Different requests to the same URL can collide.
Hashing the body requires buffering, canonicalization, secret review, size limits, authorization variation and proof that endpoint effects may be skipped. A GET representation, typed domain cache or asynchronous result resource is almost always clearer.
Body limits should follow the endpoint contract
The framework defaults allow a 64 MB body and a 100 MB in-process store. Those are technical defaults, not recommended application sizes.
When a body exceeds MaximumBodySize, it still reaches the client but is not stored. A full store stops accepting new entries until eviction creates room.
Large responses create allocation, copy, Redis bandwidth and poor eviction economics. Files normally belong in object storage and a CDN. SSE, gRPC streams and unbounded feeds do not produce the bounded completed response that output caching needs.
Locking only coalesces misses inside one process
Output caching enables resource locking by default. On one replica, the first request generates a missing entry while matching requests wait and then reuse it.
Disabling locking trades waiting for duplicate dependency work. It should happen only after measuring regeneration cost and latency.
The lock is not distributed. Ten replicas sharing Redis can all observe the same miss and regenerate once per process. Redis shares entries and tag invalidation; it does not provide one global regeneration lock.
There is also no built-in stale-while-revalidate path. After expiration, one request must generate a fresh entry while local waiters wait.
Tag eviction is not transactional
After a mutation commits, the affected tag should be evicted:
1using Microsoft.AspNetCore.OutputCaching;
2
3app.MapPut(
4 "/api/catalog/{id:int}",
5 async (
6 int id,
7 UpdateCatalogItem request,
8 CatalogWriter writer,
9 IOutputCacheStore outputCacheStore,
10 CancellationToken cancellationToken) =>
11 {
12 CatalogItem updatedItem = await writer.UpdateAsync(
13 id,
14 request,
15 cancellationToken);
16
17 await outputCacheStore.EvictByTagAsync(
18 OutputCachePolicies.CatalogTag,
19 cancellationToken);
20
21 return TypedResults.Ok(updatedItem);
22 });Evicting before commit lets another request repopulate old data while the write is pending. Evicting afterward still has a race: a read can load old data before the write, wait and store its old response after eviction.
Tags provide bounded freshness, not transactional consistency. Strict read-after-write behavior requires a monotonic data version in the key, coordinated population or no output caching on that read.
Tag granularity follows the read model. One global tag causes broad regeneration. One tag per row can create huge metadata sets for list responses. Aggregate tags such as catalog:electronics are often a better balance.
In-process versus Redis is a scope decision
The in-process store is fastest and has no external dependency. Each replica has separate entries and tag eviction, memory use multiplies and every deployment starts cold.
The Redis output-cache provider shares entries and invalidation:
1using Microsoft.AspNetCore.OutputCaching.StackExchangeRedis;
2
3string redisConnection = builder.Configuration.GetConnectionString(
4 "OutputCache")
5 ?? throw new InvalidOperationException(
6 "The output cache Redis connection is missing.");
7
8builder.Services.AddStackExchangeRedisOutputCache(
9 (RedisOutputCacheOptions options) =>
10 {
11 options.Configuration = redisConnection;
12 options.InstanceName = "catalog-api:";
13 });This is not AddStackExchangeRedisCache. Output caching needs IOutputCacheStore behavior, including atomic tag metadata. A generic IDistributedCache adapter is the wrong abstraction.
Redis adds network latency, memory cost, large-payload bandwidth and a new failure mode. During store failure the endpoint can still execute, which preserves availability but can suddenly send full traffic to the origin dependency.
Redis is justified only when shared entries and cross-replica invalidation provide more value than those costs.
Conditional requests save bandwidth
Fresh cached entries can answer matching If-None-Match or If-Modified-Since with 304 Not Modified.
1app.MapGet(
2 "/api/catalog/version",
3 async (
4 HttpContext httpContext,
5 CatalogVersionReader versionReader,
6 CancellationToken cancellationToken) =>
7 {
8 CatalogVersion version = await versionReader.ReadAsync(
9 cancellationToken);
10
11 httpContext.Response.Headers.ETag =
12 $"\"{version.Value}\"";
13
14 return TypedResults.Ok(version);
15 })
16 .CacheOutput(OutputCachePolicies.Catalog);The ETag must represent the complete response representation, not merely one row. Conditional requests save transfer; they do not refresh expired entries or replace invalidation.
Dynamic policies still need bounded definitions
.NET 11 introduces IOutputCachePolicyProvider, allowing named policies to come from a controlled provider rather than only static options.
Remote policy lookup on every request would put a new dependency before cache access. A small validated policy set should be cached locally, with versioned prefixes when variation or lifetime semantics change.
Existing entries do not transform when a policy changes. Reducing the configured storage lifetime does not retroactively shorten existing entries’ expiration, so an immediate change needs eviction, a new namespace or a serving-time policy. Disabling lookup bypasses old entries without deleting them. Adding a variation dimension normally produces different keys, but old entries remain until expiry or eviction.
IOutputCachePolicy itself participates before lookup, before serving and after response generation. Custom policy code sits on a hot path; database calls, remote configuration, large allocations and attacker-controlled key material defeat the purpose.
Choose the right cache layer
| Layer | Cached unit | Endpoint runs on hit? |
|---|---|---|
| Output cache | Status, headers, body bytes | No |
| HTTP response cache | HTTP representation under RFC 9111 | No |
HybridCache | Typed application data | Yes |
IMemoryCache | In-process objects | Yes |
| CDN | Edge HTTP representation | No origin call |
Data caching is preferable when authorization must run every time, several endpoints reuse the value, only one dependency call is expensive or personalized output combines shared and private data.
Output caching fits anonymous, bounded, expensive, repeatable responses with a small explicit variation space.
Stacked caches need one freshness budget. A five-minute data cache beneath a one-minute output cache can return data older than five minutes depending on timing.
Measure avoided cost, not only hit ratio
Useful bounded telemetry includes hit, miss, bypass, store failure, policy, route template, body size, generation duration, lock wait, eviction reason, Redis latency and estimated key cardinality.
Raw cache keys do not belong in metrics. They can contain hosts, paths, query values and personal data.
A 99 percent hit ratio on a cheap endpoint may waste memory. A 20 percent hit ratio on an expensive report may be valuable. Avoided database, CPU and serialization cost should be compared with cache latency, memory, invalidation complexity and tolerated staleness.
Test the HTTP behavior
The risky behavior appears only when routing, authentication, headers, middleware and endpoint execution interact.
1using System.Net.Http.Json;
2using Microsoft.AspNetCore.Mvc.Testing;
3
4public sealed record CachedResponse(int Generation);
5
6public sealed class OutputCacheContractTests :
7 IClassFixture<WebApplicationFactory<Program>>
8{
9 private readonly HttpClient _client;
10
11 public OutputCacheContractTests(
12 WebApplicationFactory<Program> applicationFactory)
13 {
14 _client = applicationFactory.CreateClient();
15 }
16
17 [Fact]
18 public async Task CachedEndpoint_WhenRequestIsIdentical_ReplaysResponse()
19 {
20 CachedResponse? first = await _client
21 .GetFromJsonAsync<CachedResponse>("/test/output-cache?value=1");
22
23 CachedResponse? second = await _client
24 .GetFromJsonAsync<CachedResponse>("/test/output-cache?value=1");
25
26 Assert.NotNull(first);
27 Assert.NotNull(second);
28 Assert.Equal(first.Generation, second.Generation);
29 }
30
31 [Fact]
32 public async Task CachedEndpoint_WhenQueryChanges_GeneratesVariant()
33 {
34 CachedResponse? first = await _client
35 .GetFromJsonAsync<CachedResponse>("/test/output-cache?value=1");
36
37 CachedResponse? second = await _client
38 .GetFromJsonAsync<CachedResponse>("/test/output-cache?value=2");
39
40 Assert.NotNull(first);
41 Assert.NotNull(second);
42 Assert.NotEqual(first.Generation, second.Generation);
43 }
44}The test matrix should also cover language and media variants, irrelevant query values, authenticated bypass, Set-Cookie, non-200 responses, expiry, tag eviction, concurrent misses, oversized bodies, 304 and store restart.
Authenticated policies warm entries as one user and read as another in both orders. Multi-replica tests use several instances and one Redis store to expose distributed invalidation, regeneration, outage behavior and rolling-version compatibility.
Recommended default
A safe starting point is a small set of anonymous, expensive, bounded GET responses. Each receives a named policy, query allowlist, canonical header values, conservative body limit, short lifetime, explicit tag and versioned response prefix.
Expansion should follow measurement and security tests. Personalized output, huge bodies, POST and a distributed store are unsuitable starting points.
Output caching is powerful because it bypasses almost the entire application. That is also its risk. The cache cannot understand permissions, cultures, features or database rows behind the bytes. The key and invalidation strategy must carry that meaning explicitly.
Further reading
Related articles

- 16 min read
Production Rate Limiting in ASP.NET Core
Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …

- 12 min read
Problem Details in ASP.NET Core and .NET 11
builder.Services.AddProblemDetails() registers infrastructure. It does not create an error contract. An ASP.NET Core request can fail during …

- 10 min read
What Matters in ASP.NET Core 11
ASP.NET Core 11 has no single feature that fundamentally changes how web applications are built. That is not a criticism. Mature frameworks …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
