ASP.NET response caching explained

Posted: (EET/GMT+2)

 

Response caching lets you tell clients and proxies that a response can be reused for a while instead of making a new HTTP request back to your application every time. In ASP.NET Core, you can control this with a built-in middleware system and the [ResponseCache] attribute.

First, add and enable the caching middleware in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseResponseCaching();
    app.UseMvc();
}

Then, above a controller action, use the [ResponseCache] attribute:

[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
public IActionResult GetTime()
{
    return Content(DateTime.UtcNow.ToString("O"));
}

This adds the appropriate HTTP cache headers (for example Cache-Control: public,max-age=60), and the middleware will serve cached responses for identical requests when possible. You can also vary by query string or headers:

[ResponseCache(Duration = 60, VaryByQueryKeys = new[] { "page" })]
public IActionResult List(int page = 1) { ... }

Keep in mind that response caching is different from in-memory caching. Response caching is about the HTTP protocol replies (with headers and intermediate processing), while in-memory caching is about storing data in your server code. You can use both together when it makes sense.