ASP.NET - Response Caching Techniques

Response caching stores server responses so the same request does not need to be processed repeatedly. When a cached response is available, the server can return it immediately, reducing processing time and improving overall performance.


How Response Caching Works
When a request is made, the server checks whether a cached response already exists. If it does, that response is sent back instead of executing the endpoint again. Caching is usually controlled by HTTP headers that define how long a response should be reused.


Cache Control Headers
Headers like Cache-Control, Expires and Vary tell clients and proxies how caching should behave. They specify whether a response is cacheable, how long it stays valid and whether different request values should produce different cached responses. Proper header use is key to effective caching.


Server-Side Response Caching
ASP.NET Core provides response caching middleware that stores responses in memory. This works best for public, read-only data that does not change often. It avoids unnecessary processing and improves response times under heavy load.


Client and Proxy Caching
Browsers and reverse proxies can also cache responses when allowed. This reduces repeated requests reaching the server at all. Using client-side caching is especially effective for static or semi-static API responses.


Why Response Caching Matters
Caching reduces server load, speeds up responses and improves scalability. It allows applications to handle more users without increasing hardware resources.


Example

var builder = WebApplication.CreateBuilder(args);

// Add response caching service
builder.Services.AddResponseCaching();

var app = builder.Build();

// Enable caching middleware
app.UseResponseCaching();

app.MapGet("/time", () =>
{
    return DateTime.Now.ToString();
})
.WithMetadata(new ResponseCacheAttribute
{
    Duration = 30
});

app.Run();

Result
Requests to /time return the same response for 30 seconds, avoiding repeated execution of the endpoint.