How does the newer Output Caching middleware (introduced in .NET 7) differ from Response Caching middleware?
Short answer
Output Caching (UseOutputCache(), CacheOutput() policies) caches the response server-side (unlike Response Caching, which relies on client/proxy cache-control headers and doesn't actually store responses server-side by default), supports programmatic cache invalidation via tags…
Advertisement
AModel answer
Output Caching (UseOutputCache(), CacheOutput() policies) caches the response server-side (unlike Response Caching, which relies on client/proxy cache-control headers and doesn't actually store responses server-side by default), supports programmatic cache invalidation via tags, and offers a more flexible policy-based configuration model (varying by query string, header, or custom logic) -- generally the more powerful and recommended choice for server-side output caching going forward.
builder.Services.AddOutputCache(options => {
options.AddPolicy("ProductsPolicy", policy => policy.Expire(TimeSpan.FromMinutes(5)).Tag("products"));
});
app.UseOutputCache();
app.MapGet("/products", () => GetProducts()).CacheOutput("ProductsPolicy");
// Invalidate all cached responses tagged 'products' when data changes:
await outputCacheStore.EvictByTagAsync("products", default);Real-world example
An e-commerce API uses Output Caching with tag-based invalidation, so updating any product immediately evicts all cached product-listing responses via EvictByTagAsync, rather than waiting for a fixed TTL to naturally expire potentially stale cached data.
Likely follow-ups
- Why is tag-based invalidation not available with Response Caching middleware?
- Can Output Caching be configured to use a distributed store like Redis instead of in-memory?
Related topics