What is response caching middleware in ASP.NET Core, and how does it differ from application-level data caching?
Short answer
Response caching (via UseResponseCaching middleware and [ResponseCache] attributes) caches entire HTTP responses (based on cache-control headers, varying by query string/headers) at the HTTP layer, serving cached responses directly without even invoking the controller action…
Advertisement
AModel answer
Response caching (via UseResponseCaching middleware and [ResponseCache] attributes) caches entire HTTP responses (based on cache-control headers, varying by query string/headers) at the HTTP layer, serving cached responses directly without even invoking the controller action again -- distinct from application-level data caching (IMemoryCache/IDistributedCache), which caches specific pieces of data used within your business logic, potentially still requiring the full request pipeline to execute.
builder.Services.AddResponseCaching();
app.UseResponseCaching();
[ResponseCache(Duration = 60, VaryByQueryKeys = new[] { "category" })]
[HttpGet]
public IActionResult GetProducts(string category) => Ok(_products.Where(p => p.Category == category));Real-world example
A public product catalog API caches entire GET /products?category=electronics responses for 60 seconds using response caching middleware, avoiding the full controller execution (including data-layer caching) entirely for repeated identical requests within that window.
Likely follow-ups
- How does VaryByQueryKeys affect what counts as a 'unique' cached response?
- How does response caching interact with a CDN sitting in front of the API?
Related topics