How to use response caching middleware in ASP.NET Core

By FoxLearn 1/4/2025 2:29:26 AM   46
In ASP.NET Core, response caching can significantly improve application performance by reducing the load on the web server.

ASP.NET Core is a popular framework for building high-performance web applications across Windows, Linux, and MacOS, supports various caching methods. While it doesn't have a built-in Cache object, it offers support for in-memory caching, distributed caching, and response caching, all of which contribute to enhanced performance.

Understanding Response Caching

Response caching in ASP.NET Core involves using HTTP response headers to cache web server responses, reducing the number of requests to the server and decreasing latency. Unlike output caching, it doesn't store responses in the server's memory but can use memory by default or be configured with custom storage providers. It informs web browsers to cache content, improving performance by serving subsequent requests from the client’s cache.

Creating a new ASP.Net Core project with an example Controller for building and executing RESTful HTTP services.

Next, add the required package to enable response caching middleware. You can do that by selecting the newly created project in the Solution Explorer and reference the Microsoft.AspNetCore.ResponseCaching package using the NuGet Package Manager.

Configure response caching middleware in ASP.NET Core

To enable response caching, add the middleware to the IServicesCollection in the ConfigureServices method using services.AddResponseCaching().

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

Then, include the middleware in the request processing pipeline with the UseResponseCaching extension method.

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

Response caching options in ASP.NET Core

The response caching middleware in ASP.Net Core offers three options for control:

  • SizeLimit: Sets the maximum cache size (default is 100 MB).
  • UseCaseSensitivePaths: Determines if responses are cached based on case-sensitive paths.
  • MaximumBodySize: Specifies the largest cacheable response body size (default is 64 MB).

These options can be configured in the ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching(options =>
     {
          options.UseCaseSensitivePaths = true;
          options.MaximumBodySize = 1024;
     });
    services.AddMvc();
}

Using the ResponseCache attribute in controller methods in ASP.NET Core

After configuring the middleware, the [ResponseCache] attribute can be used on controller methods to set HTTP headers for response caching.

Key parameters include:

  • Duration: Specifies the caching duration (in seconds).
  • Location: Defines where the response should be cached (Any, Client, None).
  • NoStore: Indicates whether the data should be stored.
  • CacheProfileName: Names the cache profile.
  • VaryByHeader: Specifies the Vary response header.
  • VaryByQueryKeys: Determines query parameters for caching.

For example:

[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
public IActionResult AboutPage()
{
    ViewData["Info"] = "Welcome to the About page. Last updated on: " + DateTime.Now.ToString();
    return View();
}

In this example, the response for the AboutPage action will be cached for 60 seconds on the client side.

The middleware only caches responses with an HTTP status code of 200; errors and error pages are ignored.