How to use response cache Middleware in ASP. Net core

Time:2021-6-10

Now more and more developers choose ASP. Net core to build high-performance and modern web programs, and run on windows, Linux and MacOS. Cache is one of the most important tasks of high performance. Although there is no built-in cache object in ASP. Net core, the following three cache methods can be realized by using nuget’s external extension.

  • In-memory caching
  • distributed caching
  • response caching

In the previous article, I discussed how to implement memory cache and distributed cache in ASP. Net core. In this article, I will explain the response cache and its benefits, and then look at how to integrate in ASP. Net coreresponse cacheMiddleware.

Response Cache

The principle of response cache is toHttp Response HeaderSet some cache related parameters to cache the response. In the header, you can specify whether to cache the response for all request requests or some optional request requests. Note that it is not output cache, which means that ASP. Net core will not cache the response in webserver.

In fact, response cache is a better and more convenient caching mechanism. It sets some cache related response headers in HTTP header to notify the browser to cache the specified content, which avoids a large number of unnecessary requests from the client to the web server. Subsequent requests are returned directly from the local client cache, There is no round trip time for both sides.

Configure response cache

To useResponse Cache, which needs to be injected into the servicecollection container. The code is as follows:


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

After injection into the container, use theUseResponseCaching()Add it to theRequest processing pipelineThe code is as follows:


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

Configuration item for response cache

The response caching middleware provides three options to realize the customization of certain programs

  • SizeLimit

It is used to specify the maximum cache size of the response cache, which is 100 MB by default.

  • UseCaseSensitivePaths

Used to specify whether the response cache is case sensitive to the cache key.

  • MaximumBodySize

Specifies the maximum size of a single cache entry. The default size is 65mb.

The following code snippet shows how to configure with these three options.


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

Using the responsecache feature

So far, the middleware has been configured and can now be used on the action method [ResponseCache]Of course, you can also use the following options in the constructor of an attribute.

  • Duration

Specifies the lifetime of the response cache.

  • Location

It is used to specify the location of response cache, including any, client and none.

  • NoStore

Used to specify whether data is stored on the client.

  • CacheProfileName

Used to specify the name of the cache profile.

  • VaryByHeader

Specifies the vary response header.

  • VaryByQueryKeys

Cache based on querystring parameter.

Next, in theController.IndexMethod uses the responsecache feature to cache the output content for 30s, as shown in the following code:


    public class HomeController : Controller
    {
        [ResponseCache(Duration = 30)]
        public IActionResult Index()
        {
            ViewData["Message"] = "The current time is:" + DateTime.Now.ToString();
            return View();
        }
    }

Here’s what’s going onIndex.cscode:


@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <h1> @ViewData["Message"]</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

How to use response cache Middleware in ASP. Net core

Let’s take a lookHTTP response headerWhether some changes have been made.

How to use response cache Middleware in ASP. Net core

From the picture aboveCache-Control: public,max-age=30It can be seen that the response has been cached for 30s, but it should be noted that,Response caching MiddlewareOnly caching the server response of HTTP 200 means that non-200 or some error pages will not be cached.

More aboutResponse caching MiddlewareFor reference: https://docs.microsoft.com/en…

Translation link: https://www.infoworld.com/art…

More high quality dry goods: see my GitHub: csharptranslate

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]