In ASP.NET Core, what does output caching do, and why do AddOutputCache and UseOutputCache on their own cache no responses?
answer
- server-side copy of the whole response
- no policy, the middleware steps aside
- CacheOutput() or [OutputCache]
- AddBasePolicy covers every endpoint
- Age header on a cache hit
basics
~20 sOutput caching stores an endpoint's whole response (status, headers and body) on the server and replays it without running the endpoint. AddOutputCache and UseOutputCache only make it available; nothing is cached until a policy applies to the request.
solid answer
~40 s`builder.Services.AddOutputCache()` registers `OutputCacheOptions` and the default in-memory `IOutputCacheStore`, and `app.UseOutputCache()` adds the middleware. On every request the middleware collects policies: base policies added with `AddBasePolicy`, an `IOutputCachePolicy` that `.CacheOutput()` put on the endpoint, or an `[OutputCache]` attribute. If it finds none, it calls the next middleware and does nothing else, so a bare setup caches nothing. Once a policy applies, the first eligible request runs the endpoint while the middleware buffers the response and stores it; later requests with the same cache key are answered from the store, with an `Age` header, and the handler never runs. The policy decides eligibility, the key and the lifetime, which is 60 seconds unless something sets another. The middleware ships in the shared framework (`Microsoft.AspNetCore.OutputCaching`), so the in-memory store needs no package.
code
csharp · 11 linesbuilder.Services.AddOutputCache();
var app = builder.Build();
app.UseOutputCache();
app.MapGet("/lineup", (FestivalDb db) => db.Acts.ToListAsync())
.CacheOutput();
app.MapGroup("/stages")
.CacheOutput()
.MapGet("/", (FestivalDb db) => db.Stages.ToListAsync());go deeper
Recall the two registration calls and the three ways to attach a policy: CacheOutput, [OutputCache] and AddBasePolicy. Say clearly that nothing is cached until one of them applies.
Explain what the middleware does per request: collect policies, compute a key, serve from the store or buffer and store the response. Mention the Age header and the 60-second default lifetime.
Show you know the cache is server-side only and adds no Cache-Control, and that default eligibility rules (anonymous GET or HEAD, status 200) explain most it-does-not-work reports.
Frame output caching against data caching: it caches whole representations, so it fits public, shared pages and fits badly where responses differ per user or must be invalidated precisely.
## What output caching is **Output caching** is ASP.NET Core's server-side response cache. The `OutputCacheMiddleware` sits in the request pipeline, captures the complete response an endpoint produced (status code, headers and body bytes) and keeps it in an `IOutputCacheStore`. When a later request maps to the same **cache key**, the middleware writes the stored response straight back and the endpoint, its database query and its serialization never run. It works for Minimal APIs, controllers and Razor Pages alike, because it hangs off endpoint metadata rather than off any one programming model. It is different from caching *data*: `IMemoryCache` or `HybridCache` hold objects your code asks for, while the output cache holds finished HTTP responses and is driven by policies, not by calls in your handler. ## The two registration calls - **`builder.Services.AddOutputCache()`** registers `OutputCacheOptions` (where policies are declared) and, unless another store was registered, a `MemoryOutputCacheStore` built on `MemoryCache` with a 100 MB `SizeLimit`. - **`app.UseOutputCache()`** adds `OutputCacheMiddleware` to the pipeline. Where exactly it goes is a pipeline-ordering question of its own. Neither call caches anything. The middleware's first step is to look for policies that apply to the current request: 1. every **base policy** registered with `options.AddBasePolicy(...)`; 2. an `IOutputCachePolicy` in the endpoint's metadata, which `.CacheOutput(...)` adds; 3. an `[OutputCache]` attribute on the endpoint. If the list is empty, the middleware simply awaits the next delegate. That is why a fresh project that called both methods and nothing else sees every request reach the handler. ## Turning it on On a festival site, the public line-up is the obvious candidate: ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddOutputCache(); var app = builder.Build(); app.UseOutputCache(); app.MapGet("/lineup", async (FestivalDb db) => await db.Acts.OrderBy(a => a.StartsAt).ToListAsync()) .CacheOutput(); // default policy, 60 s app.MapGet("/weather", () => Forecast.Now()); // no policy: never cached app.Run(); ``` `CacheOutput` is an extension on any `IEndpointConventionBuilder`, so it also works on a `MapGroup(...)` result and on `MapControllers()`. Controllers and Razor Pages usually use the attribute instead: ```csharp [HttpGet] [OutputCache(Duration = 120)] public async Task<IActionResult> Lineup() => Ok(await _db.Acts.ToListAsync()); ``` To cache *every* eligible endpoint without touching each one, add a base policy: `options.AddBasePolicy(b => b.Expire(TimeSpan.FromSeconds(30)))`. ## What is in the box | Piece | Role | |---|---| | `OutputCacheOptions` | holds base and named policies plus global settings | | `DefaultExpirationTimeSpan` | lifetime when no policy sets one: **60 seconds** | | `SizeLimit` | capacity of the default store: **100 MB** | | `MaximumBodySize` | largest body that will be stored: **64 MB** | | `UseCaseSensitivePaths` | `false`, so `/Lineup` and `/lineup` share entries | | `OutputCachePolicyBuilder` | fluent builder behind `CacheOutput(b => ...)` and `AddPolicy` | | `IOutputCacheStore` | where entries live; in memory unless you register another store | Everything above ships in the shared framework, in the `Microsoft.AspNetCore.OutputCaching` namespace, so a web project already references it. Only a different store, such as the Redis one, needs an extra package. ## Output cache versus data caches The output cache sits **in front of** the endpoint and caches the bytes it wrote, so a hit skips model binding, the handler, database access and serialization in one go. A data cache sits **inside** the handler and skips only the expensive call it wraps. The trade-off is granularity: an output cache entry is a whole representation for one cache key, so it suits public, shared responses, while anything that differs per user is better served by caching the data and rendering per request. ## How you can tell it worked | Signal | Meaning | |---|---| | Handler breakpoint not hit on the second request | served from the store | | `Age` response header present | the middleware copied a stored entry and set its age in seconds | | Information log "Serving response from cache." (event `CachedResponseServed`) | lookup succeeded; "The response has been cached." marks a store | The middleware does **not** add `Cache-Control` or `ETag` headers of its own: browsers and CDNs see whatever the endpoint wrote. Output caching is a server-side store, not an instruction to downstream caches. ## Common first mistakes - **Testing while signed in.** The default policy never caches authenticated requests, so a developer logged into the admin area sees no effect. - **Testing with POST.** Only `GET` and `HEAD` qualify by default. - **Using `[ResponseCache]`.** That attribute writes HTTP caching headers for the separate response caching middleware; it does not enable the output cache. - **Calling `UseOutputCache` without `AddOutputCache`.** The middleware cannot resolve `IOutputCacheStore`, and the app fails when the pipeline is built.
- Can a Minimal API route group enable output caching for all of its endpoints at once?Yes. `CacheOutput` is an extension method on any `IEndpointConventionBuilder`, and `MapGroup` returns a `RouteGroupBuilder`, which is one. Calling `app.MapGroup("/stages").CacheOutput()` adds the policy to the metadata of every endpoint mapped in that group, exactly as if each had called it.
- What does a client see differently when a response comes from the output cache?The status, headers and body are the stored ones, and the middleware adds an `Age` header with the entry's age in seconds. If the request carries `If-None-Match` matching a stored `ETag`, or a satisfied `If-Modified-Since`, it answers `304 Not Modified` instead of sending the body.
Output caching is a print shop that keeps the master copy of a popular flyer: once one customer orders it, later customers get a copy off the pile without the designer redrawing it. But the shop only keeps flyers it was told to keep; without that instruction every order is drawn from scratch.
- AddOutputCache alone starts caching every GET endpoint automatically.
- Output caching works by sending Cache-Control headers to the browser.
- The in-memory output cache needs a separate NuGet package installed first.
- Putting [ResponseCache] on an action turns on the output cache middleware.
- A cached hit still runs the handler and only skips JSON serialization.