hosting tips

What is ASP.NET Core Response Caching?

Response buffering entails storing output responses. Response caching enables browsers and other clients to retrieve a server’s response swiftly and efficiently in response to subsequent requests. Response caching in ASP.NET Core reduces server burden and enhances the user experience in web applications. This blog will provide a comprehensive explanation of response caching in ASP.NET Core.

What exactly is Response Cache?

Using the response cache, the server can store responses in memory or on disc so that subsequent requests can retrieve them rapidly. Caching mechanisms examine the cache for responses whenever a server request is made. The cache returns the response rather than generating a new one. Using response caching decreases the server’s burden and the number of requests made to the server.

Note the HTTP caching directives and how they can be used to control caching behavior.

Response Header Caching

To cache the response, the ‘Client and Server’ exchange HTTP header information. How HTTP caching directives can be used to control caching behaviour. Cache-control specifies the manner in which the response can be retained. When the cache-control header is present in the response, it is the responsibility of browsers, clients, and proxy servers to honor it.

Principal Response Caching Headers appear as follows:

  • Cache-Control Pragmatism
  • Vary
  • Header with the Cache-Control directive

The Cache-Control header is the primary response caching header. To add a Cache-Control header in ASP.Net Core, use the Response object in the action method of your controller. So, let’s begin with the most prevalent cache-control directives:

This cache can either store the response on the device or in a shared location.
This Private Cache always stores Client Side Response, but does not purge the cache on the client side.
max-age: This cache-control directive indicates how long a response should be stored in the cache.
no-cache: This value denotes that the client should not store a copy of the response in its cache.
no-store: This cache is not permitted to retain the response.

Pragma Header

The Pragma header can control cache performance for ASP.NET Core. Included in the Pragma preface are server and client instructions. If the response is decorated with Cache-Control, Pragma is omitted.
Change Header

The Vary HTTP response header is included in this method’s request message, and the URL is the response’s body.
ResponseCache Property

ResponseCache attributes specify header properties for response cache headers in ASP.NET Core web applications. This attribute can be applied at either the controller or endpoint level.

Following are several input parameters for the cache attribute.

Duration

You can set or retrieve the cached duration of the response in seconds. This defines the “max-age” attribute within the “cache-control” header. The max-age header, which is used to specify the cache duration, will be generated based on the duration of this property.

Location

specifies the Location where data from a specific URL will be cached. If the Location is decorated with “ResponseCacheLocation.Client,” it functions as a cached response on the client and adds “cache-control” to the private header.

In this example, the Location has the “ResponseCacheLocation” attribute.”None” operates as “cache-control”, and the “Pragma” header is set to “no-cache.”

Note: If you are able to examine the cached response, follow the links on web pages or use Swagger to execute API endpoints in the browser.

Otherwise, if you attempt to refresh the page or revisit the URI, the browser will always request a new response from the server regardless of the response cache settings.

Public

public HomeController class: Controller [HttpGet]
[ResponseCache(Duration = 180, Location = ResponseCacheLocation.Any, LocationType = Any)]
public IActionResult getCache() return Ok($"Responses will be generated at DateTime.Now");

This Duration property generates the max-age header, which is used to set the cache duration to 3 minutes (180 seconds). Location defines the Location within the cache-control payload.

Consequently, the API endpoint and these response headers:

cache-control: public with a maximum age of 180

The response arrives from the disc cache, as indicated by the status code.

Status Code: 200 Confidential

Simply set the Location property to private in ResponseCacheLocation.Client:

public HomeController class: Controller [HttpGet]
Response Cache (Duration: 180, Location: ResponseCacheLocation.Client)
public IActionResult getCache() return Ok($"Responses will be generated at DateTime.Now");

This modifies the cache control header value to private, allowing only the client to cache the response.

cache-control: private,max-age=180 No-Cache

Now, let’s update Location to ResponseCacheLocation. None:

public HomeController class: Controller [HttpGet]
ResponseCache(Duration: 180; Location: ResponseCacheLocation.None)
public IActionResult getCache() return Ok($"Responses will be generated at DateTime.Now");

Due to the cache-control and pragma headers being set to no-cache, the client cannot use a cached response without first verifying it with the server.

cache-control: no-cache,max-age=180

pragma: no-cache

Each time, the server generates a new response, and the browser does not cache the response.
NoStore

Gets or sets the value that determines whether the data should be stored. If NoStore is decorated with the value “true”, “cache-control” is set to “no-store” It ignores “Location” and the parameter’s values; otherwise, it returns “None”.

public HomeController class: Controller [HttpGet]
[ResponseCache(Duration = 180 days, Location = ResponseCacheLocation.Any,NoStore = True
public IActionResult getCache() return Ok($"Responses will be generated at DateTime.Now");

This specifies no-store as the response header cache control. This indicates that the response should not be cached by the client:

cache-control: do not persist the VaryByHeader header

Sets or receives the value of the “Vary” response header. ResponseCache’s VaryByHeader property enables the setting of the vary header:

Now that User-Agent is the value for the VaryByHeader property, the cached response will be used for requests coming from the same client device. When the value of User-Agent on the client device changes, a new response is retrieved from the server. Let’s confirm this.

public HomeController class: Controller [HttpGet]
[ResponseCache(Duration = 180 days, Location = ResponseCacheLocation.Any,VaryByHeader="User-Agent")]
public IActionResult getCache() return Ok($"Responses will be generated at DateTime.Now");

Check the headers of the response for the Vary header:

vary: User-Agent

When the application is executed in desktop mode, the response header “Vary” will contain the value “User-Agent” (see below).

Mozilla/5.0 (Windows NT 10.0; Win64; x64) is the user agent. AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 similar to Mac OS X) is the user-agent for the Safari/537.36 browser. AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1

VaryByQueryKeys Attribute

The VaryByQueryKeys property can be used to instruct the server to generate a new response whenever the response changes. Changes have been made to the query string parameters.

public HomeController class: Controller [HttpGet]
[ResponseCache(Duration = 180 days, Location = ResponseCacheLocation.Any, VariableByQueryKeys = new string[] "Id" )]
public IActionResult getCache() return Ok($"Responses will be generated at DateTime.Now");

For instance, when the Id value and URI both alter and a new response must be generated:

/api/Home?Id=1

/api/Home?Id=2 Profile Cache

In this project, Response Cache attributes can be used as the majority of action methods have identical input parameters. All ASP.Net Core parameter options are associated with a Programme class and its name, which can be used in the Response Cache attribute to eliminate duplicate parameter configurations.

Cache3 is a novel cache profile with a duration of three minutes and a public location.

builder.Services.AddControllers (option => 'controllers')
option.Profiles Cache.); Add("Cache3", new CacheProfile() Duration = 180, Location = ResponseCacheLocation.Any ); );
public HomeController class: Controller [HttpGet]
[ResponseCache (ProfileName="Cache3")]
public IActionResult getCache() return Ok ($"Responses are generated on (DateTime.Now)"); public IActionResult flushCache()
The cache-control response as defined (see below):
cache-control: public with maximum age of 180

Caching Middleware

It is possible to write middleware that adds a response cache, but this implementation adds one to every page.

Program.cs Record

builder.Services.AddControllers(); builder.Services.AddResponseCaching(); var builder = WebApplication.CreateBuilder(args);

const app = builder.Build();

app.Run(); app.MapControllers(); app.UseResponseCaching ()
public HomeController class: Controller [HttpGet]
[ResponseCache(Duration = 180 days, Location = ResponseCacheLocation.Any, VaryByQueryKeys = new string [] "Id"
IActionResult public getCache(int Id).
return Ok($"Responses are generated on Id:Id at DateTime.Now");

Add the response caching middleware with the AddResponseCaching() method, and then configure the application to use it with the UseResponseCaching() method.

That is all. Having enabled response caching middleware, VaryByQueryKeys should now function.

Let’s launch the application and navigate to /Home?id=1:

The response to Id:1 was generated at 23-05-2022 05:52:50.

When the query string was altered, the server generated a new response.

Modify the query string to /Home?id=2:

The response for Id:2 was generated at 23-05-2022 05:53:45.

The response caching feature of ASP.NET Core enables web applications to scale and perform more efficiently. It is possible to accelerate and enhance the efficiency of page loading by caching responses at the server or client level.

You can configure caching middleware in ASP.NET Core to cache responses based on URL path, query string parameters, and HTTP directives. In addition, you can tailor the caching behavior with options such as cache expiration times, cache location, and cache key prefixes.

ASP.NET Core’s response caching enables you to increase user satisfaction and reduce hosting expenses. When developing a high-traffic website or web application, response caching should be regarded as an essential optimization technique.

ASP.NET Core 8 Hosting Recommendation

HostForLIFE.eu

HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.