
Response Caching Is Not Output Caching: Who Really Caches Your API Responses
- كاتب موثّق
- .NET 10
محتويات المقال
/products/featured endpoint runs the same database query thousands of times a minute, so a developer adds AddResponseCaching(), UseResponseCaching() and a Cache-Control: public, max-age=60 header. A quick test with curl looks perfect: the handler runs once, then every call for a minute comes from memory. After the deploy, the database dashboard doesn't move. The mobile app's HTTP client sends Cache-Control: no-cache on every request, a setting someone added years ago to avoid stale screens, and the middleware obeys it. And when marketing edits the featured list, there's no way to clear what browsers and the CDN already keep.
The common misconception
[ResponseCache] attribute looks like server configuration. And before .NET 7 this was the only built-in way to cache whole responses, so years of tutorials present it as the server cache.
What actually happens
Response caching is an HTTP cache inside your app
200 answer to a GET or HEAD, marked public with a freshness lifetime such as max-age=60, with no Set-Cookie header in the response and no Authorization header in the request. Your app's only lever is the headers it sends.
The client gets a vote
Cache-Control header from the client, and the docs say plainly that there's "no developer control" over this. Browsers often send no-cache or max-age=0 when a page is refreshed. Tested on .NET 10: plain requests were served from memory, while three requests with Cache-Control: no-cache ran the handler three times. Each forced response also replaced the stored copy.
Your headers reach everyone else too
Cache-Control: public, max-age=60 isn't a private note to the middleware. It travels with the response and tells the browser and every proxy or CDN on the way to keep it for a minute. Those copies are out of your reach. And [ResponseCache] is an MVC filter: on a minimal API endpoint it compiled, added no header, and nothing was cached.
Output caching: the server decides
no-cache requests were still served from the cache, and the cached responses carried no Cache-Control header, so browsers and proxies weren't told to keep anything. Even an endpoint that set Cache-Control: no-store was cached, because the policy wins.
The fix: let the server own its cache
Catalog service, registered as scoped:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddScoped<Catalog>();builder.Services.AddResponseCaching();var app = builder.Build();app.UseResponseCaching();app.MapGet("/products/featured", async (HttpContext ctx, Catalog catalog) =>{ // Also tells browsers and every proxy on the way to keep it ctx.Response.Headers.CacheControl = "public, max-age=60"; return await catalog.GetFeaturedAsync();});// A request with "Cache-Control: no-cache" skips the cache entirelyapp.Run();using Microsoft.AspNetCore.OutputCaching;var builder = WebApplication.CreateBuilder(args);builder.Services.AddScoped<Catalog>();builder.Services.AddOutputCache(o => o.AddPolicy("catalog", p => p.Expire(TimeSpan.FromMinutes(1)).Tag("catalog")));var app = builder.Build();app.UseOutputCache();// Stored on the server; request headers can't bypass itapp.MapGet("/products/featured", (Catalog catalog) => catalog.GetFeaturedAsync()).CacheOutput("catalog");app.MapPut("/products/{id:int}", async (int id, Product product, Catalog catalog, IOutputCacheStore cache, CancellationToken ct) =>{ await catalog.SaveAsync(id, product, ct); await cache.EvictByTagAsync("catalog", ct); // next GET rebuilds it return Results.NoContent();});app.Run();PUT handler is the part response caching can't give you. After a write, EvictByTagAsync drops every entry tagged catalog, so the next read rebuilds it instead of serving a stale list for up to a minute.
no-cache | ||
EvictByTagAsync by tag | ||
IOutputCacheStore |
How to apply it in your project
Find every response cache Search for UseResponseCaching,[ResponseCache]and code that setsCache-Control: public. For each one, write down whether the goal is client and CDN caching or less work on the server.Move server-side caching to output caching Register AddOutputCachewith named policies, callUseOutputCacheafterUseCors,UseAuthenticationandUseAuthorization, and attach policies withCacheOutputor[OutputCache].Evict on writes Tag cached endpoints by the data they show, and call EvictByTagAsyncin the handlers that change that data.Set client headers on purpose Keep Cache-Control: public, max-ageonly on responses that are safe for any browser or CDN to keep. Sendprivateorno-storeon everything that depends on the user.
Key takeaways
The response caching middleware is an RFC 9111 HTTP cache: it follows headers, and the client's no-cachemakes it fetch a fresh response.Cache-Control: publictells browsers and proxies to cache too, and you can't evict their copies.Output caching is controlled by server policies: clients can't bypass it, and tags let you evict entries after writes. Output caching locks concurrent misses for the same entry; response caching runs the handler for every one of them. Keep personalized responses out of both: never mark them public, and putUseOutputCacheafter authentication.
التعليقات (0)