Response Caching In ASP.NET Core

In this article, you will learn about Response Caching in ASP.NET Core.

Introduction

Response Caching adds a cache related header into the response when action, controller, or middle layer is decorated with the ResponseCache attribute. Unlike Output cache, it does not store HTTP response at server, it just adds "Cache-Control" header in the response. It helps us to reduce the number of requests made by the client or proxy to the Web Server. It also helps to improve the performance of Web Server by reducing the amount of work done by the web server to generate the response. The "Cache-Control" header is used by the HTTP header.

The following common cache directives are used by HTTP header.

  • Public
  • Private
  • No-cache
  • Pragma
  • Vary

Following are some properties of ResponseCache attribute,

  • Duration It is maximum time in seconds the response will be cached. If it is not working, no store property is set to true.
  • Location It is the place where cache response might be stored. The default value is Any.
  • NoStore Based on the value of this property, cache mechanism decides whether cache is stored or not. When it is set to true, then Duration and Location are ignored.
  • VaryByHeader Any value set to this property will be written with the response. If the header value has changed, the cache version becomes invalid.
  • CacheProfileName Cache profile name that is used to do response cache.
  • Order The order of the filter.

The value of the Cache-Control header could be Public, Private, no-cache, Pragma, and vary. Let’s discuss each one of them. I am using Fiddler to check the response of the request in this article.

Public

The public response directive indicates that it allows to cache any caching mechanism. This directive can be used when our page is independent of user; i.e., same page is available for all users, such as static help page.

Controller’s Action method

  1. [ResponseCache(Duration = 60)]  
  2. [Route("home/LogData")]  
  3. public IActionResult LogData() {  
  4.     return View();  
  5. }  

Output


Private

The "private" value for Cache-Control header indicates that the value for the response message is intended for single user. It is not stored in shared cache. To make it private, we need to specify "Location = ResponseCacheLocation.Client" along with ResponseCachen attribute.

Controller’s Action method

  1. [ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]  
  2. [Route("home/LogData1")]  
  3. public IActionResult LogData1() {  
  4.     return View("LogData");  
  5. }  
Output

 


no-cache

The "no-cache" request directive indicates that cache has not stored any part of either response or request. To make it no-cache, we need to specify "Location = ResponseCacheLocation.None" along with ResponseCachen attribute. 

Controller’s Action method

  1. [ResponseCache(Duration = 60, Location = ResponseCacheLocation.None)]  
  2. [Route("home/LogData2")]  
  3. public IActionResult LogData2() {  
  4.     return View("LogData");  
  5. }  

Output


Pragma

This header field allows backwards compatibility with HTTP/1.0 caches, so if the client sets "no-cache" header, they will understand. This header is ignored, when Cache-Control is present in header.

Vary

The header is set only when the VaryByHeader property is set. It contains the comma separated values that are used to vary the cache entry. When this property contains comma separated values, cache may have different versions of cache value.

Controller’s Action method

  1. [ResponseCache(Duration = 60, VaryByHeader = "User-Agent")]  
  2. [Route("home/LogData3")]  
  3. public IActionResult LogData3() {  
  4.     return View("LogData");  
  5. }  

Output


Configure response cache by using CacheProfileName property

As described above, we can configure response cache for controller action method. Instead of defining response cache for individual action i.e. duplicating cache setting, we can use cache profiles to configure as options in ConfigureServices method in startup class. Property value defined in cache profile will be used as the defaults and if any property is defined with ResponseCache, the attribute will be the overridden property value defined in the cache profile.

In the following example, I have defined two cache profiles “default” and “Mycache”. In Home Controller, I have used “MyCache” profile for cache response.

Startup.cs

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.AspNetCore.Http;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Extensions.DependencyInjection;  
  6. namespace WebApplication {  
  7.     public class Startup {  
  8.         public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  9.             app.UseMvc();  
  10.             app.UseResponseCaching();  
  11.             app.Run(context => {  
  12.                 return context.Response.WriteAsync("Hello Readers!");  
  13.             });  
  14.         }  
  15.         public void ConfigureServices(IServiceCollection services) {  
  16.             services.AddMvc((options) => {  
  17.                 options.CacheProfiles.Add("default"new CacheProfile() {  
  18.                     Duration = 60,  
  19.                         Location = ResponseCacheLocation.None  
  20.                 });  
  21.                 options.CacheProfiles.Add("MyCache"new CacheProfile() {  
  22.                     Duration = 60,  
  23.                         Location = ResponseCacheLocation.Any  
  24.                 });  
  25.             });  
  26.             services.AddResponseCaching();  
  27.         }  
  28.     }  
  29. }  

Homecontroller.cs

  1. [ResponseCache(CacheProfileName = "MyCache")]  
  2. [Route("home/LogData10")]  
  3. public IActionResult LogData10() {  
  4.     return View("LogData");  
  5. }  

Output


Conclusion

Response Cache allows client to cache the response to various cache controls. It help us to reduce the number of requests a client or proxy makes to the Web Server.