ASP.NET Core 2.0 Response Caching

As you navigate between a controller with caching enabled (Home) and another one without it (Movies), you’ll notice that time isn’t been updated i.e. it's not coming from server but rather from cache.

Problem

How to cache responses in ASP.NET Core.

Solution

To an empty project, configure services and middleware for caching in Startup,

Create a controller, annotate with [ResponseCache] attribute,

The response will contain a Cache-Control header.

ASP.NET Core

As you navigate between a Controller with caching enabled (Home) and another one without it (Movies), you’ll notice that the time hasn’t been updated, i.e., it's not coming from the server but rather from the cache.

ASP.NET Core

Discussion

The Response Caching middleware is responsible for storing and serving the responses from a cache. It adds cache related headers to HTTP responses, primary one being Cache-Control.

Once middleware is set up, [ResponseCache] attribute is applied to the controller/action to enable caching. The attribute has some useful parameters to alter the behaviour of the middleware.

  • Duration: used to set cache expiry (in seconds).
  • Location: translates into Cache-Control header of public, private or no-cache.
  • VaryByQueryKeys: responses are cached based on query string parameters.
  • VaryByHeader: used to set Vary HTTP response header.
  • CacheProfileName: can point to cache profile setup in MVC middleware (see below).
    1. services.AddMvc(options =>  
    2.         {  
    3.             options.CacheProfiles.Add("default"new CacheProfile  
    4.             {  
    5.                 Duration = 30,  
    6.                 Location = ResponseCacheLocation.Any  
    7.             });  
    8.         });  
Logging

You could enable logging to view the workings of the Response Caching middleware. Below is the first request to Home/Index (see highlighted lines). The subsequent requests will go through this lifecycle, and serve the page from cache (until its expiry):

ASP.NET Core

Source

GitHub