Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the .NET Core ResponseCache cache

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to understand. NET Core ResponseCache cache". In daily operation, I believe many people have doubts about how to understand. NET Core ResponseCache cache. Xiaobian consulted all kinds of information and sorted out simple and easy to use operation methods. I hope to help you answer the doubts of "how to understand. NET Core ResponseCache cache"! Next, please follow the small series to learn together!

I. Foreword

There are two main types of cache: client-side cache (browser cache) and server-side cache. When our data does not need to be returned in time, we can consider caching the page to the client's browser for storage, and accessing the information cached by the browser directly within a certain period of time. We do this by setting the HTTP response header Cache-Control as follows:

Client (browser cache)

1. In the old version of MVC, there is a feature that can cache views (OutputCache), which can keep the request of the same parameter, read directly from the mvc cache for N periods of time, and do not go to the view logic.

//older versions of. NET practices

[OutputCache(Duration =20)]//Set expiration time to 20 seconds

public ActionResult ExampleCacheAction()

{

var time=DateTime.Now.ToString("yy MM MM DD HH mm min ss sec");

ViewBag.time= time;

return View();

}

2. There is no (OutputCache) in. Net core, and the (ResponseCache) feature is used. The official documentation states that response caching reduces the number of requests from clients or agents to web servers. Response caching can also reduce the amount of work the web server executes to generate responses. Response caching is controlled by headers that specify how you want clients, proxies, and middleware that caches responses.

/*

Duration stands for cache duration (seconds) at least 1 second

VaryByHeader Set varyRequest header information Use varyHeader facilitates dynamic diversity of content services. For example, with the Vary: User-Agent header, cache servers need to determine whether to use cached pages via UA.

Location Cache Location

None header set to "no-cache" Do not use cache

Client cache only on client side. Set the "Cache-control" title to "private."

Any cache on proxy and client. Set the "Cache-control" title to "public".

NoStore The cache must not store anything about client requests and server responses. Each request initiated by the client downloads the complete response content. If set to False Duration must be greater than 0

VaryByQueryKeys can be stored according to different parameters on the same page.

CacheProfileName Sets the cache profile value by setting different cache parameters

*/

[ResponseCache(Duration = 50, VaryByQueryKeys = new string[] { "q","name" })]

public IActionResult Index(int q,string name)

{

return View(DateTime.Now);

}

3. By running it, we can see that the browser has an extra cache-control:public,max-age=50, which means public cache on the proxy and client. max-age=50 represents 50 seconds of cache time.

4, there is also a simple and rude implementation, because we know that adding this feature only adds a cache-control:public,max-age=50 in the response request header, then we can also directly set this request header in the request response, the effect is the same.

public IActionResult Index()

{

//direct, simple and rude, don't spell it wrong ~~

Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = "public, max-age=600";

//direct two, slightly elegant

//Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()

//{

// Public = true,

// MaxAge = TimeSpan.FromSeconds(600)

//};

return View();

}

5. Sometimes in order to manage the cache configuration uniformly, we can write the cache configuration to the configuration in advance and use the name to call it. [ResponseCache(CacheProfileName ="test")], written when views are injected in Startup.

//Set some cache policies

services.AddControllersWithViews(options =>

{

options.CacheProfiles.Add("default", new CacheProfile

{

Duration = 60

});

options.CacheProfiles.Add("test", new CacheProfile

{

Duration = 30,

Location=ResponseCacheLocation.Client

});

});

6.[ResponseCache] parameter

Any cache on proxy and client. Set the "Cache-control" title to "public".

Client cache only on client side. Set the "Cache-control" title to "private."

None Each time a request is made, the cache sends the request to the server, and the server verifies whether the cache described in the request has expired. If it has not expired (note: in fact, it returns 304), the cache uses the local cache copy. The header is set to "no-cache."

Duration Sets the storage time (in seconds) of the cache. Set "max-age" in "Cache-control".

Location

The NoStore cache must not store anything about client requests and server responses. Each request initiated by the client downloads the complete response content.

VaryByHeader uses varyheaders to facilitate dynamic diversity of content services. For example, with the Vary: User-Agent header, cache servers need to determine whether to use cached pages via UA.

VaryByQueryKeys can be stored according to different parameters on the same page.

CacheProfileName Sets the cache profile value by setting different cache parameters

III. Server cache

1. ResponseCache can also set the server-side cache to store the data we return in the server and return the stored data within a certain period of time. Here I introduce a case first. Sometimes we need to pass different parameters for caching.

Case study: What do we do when we access data with paging parameters? VaryByQueryKeys We talked about this before, and it can be cached according to different parameters, so let's use it now.

Result: When we run, we find an error, which roughly means that we do not use middleware, but why do I use middleware for this cache? In fact, it is because we want to distinguish the parameters we request, and then cache our data, that is, implement server-side caching. Here we are going to use middleware provided by Microsoft.

2. We mainly inject services.AddResponseCaching(); and app.UseResponseCaching(); middleware into Startup. Server-side cache can cache page data and API data, and if our server has data, that is, cache hits, it will be taken directly from the cache and will not enter our method again.

public void ConfigureServices(IServiceCollection services)

{

services.AddResponseCaching(options =>

{

options.UseCaseSensitivePaths = false;

options.MaximumBodySize = 1024;

options.SizeLimit = 100 * 1024*1024;

});

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

app.UseResponseCaching();

}

The server-side cache configuration is as follows. When we configure the middleware and injection cache, we can use VaryByQueryKeys. When we access it once, we cache the results in our client cache, one copy each in our server cache. When we use the same browser to access the client cache information, when we switch browser access will not request our method, will first enter our middleware to see if there is a server cache, if there is a cache directly to return, if not will request the method to return, and then cache the results.

attribute

described

MaximumBodySize

Maximum cacheable size of the response body in bytes. The default value is 64 * 1024 * 1024 (64 MB).

SizeLimit

Size limit (in bytes) for response cache middleware. The default value is 100 * 1024 * 1024 (100 MB).

UseCaseSensitivePaths

Determines whether responses are cached on case-sensitive paths. The default value is false.

3, for some static files such as js,css, etc. that remain unchanged or change less all year round, you can also cache them to avoid making them always request to the server, and these static files can be cached for a longer time! If you are already using CDN, this section can be ignored for the time being... For static files,. NET Core has a separate StaticFiles middleware that also needs to be registered in the pipeline if you want to do anything with it. UseStaticFiles has several overloaded methods, in this case the one with the StaticFileOptions parameter. Because there is an OnPrepareResponse in StaticFileOptions that allows us to modify the response header to achieve the effect of HTTP caching.

app.UseStaticFiles(new StaticFileOptions

{

OnPrepareResponse = context =>

{

context.Context.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue

{

Public = true,

//for 1 year

MaxAge = System.TimeSpan.FromDays(365)

};

}

});

IV. Use of preconditions

The request must result in a server response with status code 200 (OK).

The request method must be GET or HEAD.

In Startup.Configure, response caching middleware must precede middleware that needs caching.

Authorization header must not exist.

The Cache-Control header argument must be valid and the response must be marked "public" and not marked "private."

If the Cache-Control header does not exist, the Pragma: no-cache header must not exist because the Cache-Control header, when present, overrides the Pragma header.

Set-Cookie header must not exist.

The Vary header argument must be valid and not equal to *.

The Content-Length header value (if set) must match the size of the response body.

Do not use IHttpSendFileFeature.

The Expires header and max-age and s-maxage cache directives specify responses that cannot be stale.

Response buffering must succeed. The size of the response must be less than the configured or default SizeLimit. The body size of the response must be less than the configured or default MaximumBodySize.

The 'no-store' directive must not exist in the Request or Response header field.

At this point, the study of "how to understand. NET Core ResponseCache cache" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report