Response Caching Middleware Configuration in ASP.NET Core


In this article we are going to see how to configure response caching middleware in ASP.NET Core. The response cache helps to reduce the number of requests for the web server.

This is because, when using the response cache on the ASP.NET Core, it receives data from the cache instead of the web server. The response cache attribute [response cache] determines when the response cache should be saved and how long the response cache should be stored.

When you first send a request from the client browser, it sends the request to the proxy server, and then it sends the request to the web server. The web server responds to the proxy server with a cache header. The proxy server sends the request to the client browser. For the next subsequent request from the client browser the proxy server will provide the response as long as the cache lifetime.


Let us see a small example of the response cache middleware configuration. You must first add response cache middleware to the service collection to use response cache. The following code is the ConfigureServices method in the startup.cs. Here I have added services.AddResponseCaching();

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

The next one is a Configure method, here I have configured the response cache.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
     ---
     ---
     ---

    app.Use(async (ctx, next) =>
    {
        ctx.Request.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
        {
            Public = true
        };
        await next();
    }
    );
 
    app.UseResponseCaching();
 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

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

[ResponseCache(Duration = 30)]
public IActionResult Sample()
{    
    return View("Sample", DateTime.Now);
}

The code above will show the current date and time. If you refresh the page within 30 seconds, it will show the same date and time. It will show the current date and time when you refresh the browser after 30 seconds.
 
The following is a Response Header for the Sample action. Here you can see the cache-control:public and max-age=30

Response Header 
cache-control: public,max-age=30
content-encoding: gzip
content-length: 154
content-type: text/html; charset=utf-8
date: Tue, 14 Jul 2020 15:16:01 GMT
server: Microsoft-IIS/10.0
status: 200
vary: Accept-Encoding
x-powered-by: ASP.NET

Hope this article helps you. Keep coding

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Creating a C# Azure Function with Visual Studio: Step-by-Step Guide

Exploring EventCallback in Blazor: Building Interactive Components