ASP.NET Core by Patrik

Configure Response Caching Middleware in ASP.NET Core

This snipp explains how to configure Response Caching Middleware in an ASP.NET Core app.


Add Response Caching Middleware

In Startup.ConfigureServices, add the Response Caching Middleware to the service collection using services.AddResponseCaching():

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    services.AddRazorPages(options =>
    ...
}

Configure Response Cache

Configure the app to use the middleware with the UseResponseCaching extension method, which adds the middleware to the request processing pipeline in Startup.Configure:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  ...
  app.UseResponseCaching();
  app.UseEndpoints(endpoints =>
  ...
}

Set ResponseCache attribute

In a controller action, add the [ResponseCache] attribute. The response cache middleware only works if the response cache attribute is added to the action method or controller.

[ResponseCache(Duration = 300)]
public class ImagesController : Controller
{
  ...

The following is a Response Header. It shows the cache-control:public and max-age=300

Response Header 

cache-control: public,max-age=300
status: 200
...
x-powered-by: ASP.NET


Comments

Leave a Comment

All fields are required. Your email address will not be published.