Example of static resources cached by ASP. NET Core: asp. netcore
Background
Caching style sheets, JavaScript, image files, and other static resources can improve the performance of your website. On the client side, a static file is always loaded from the cache, which reduces the number of requests to the server and the time for obtaining the page and its resources. On the server side, because they have fewer requests, the server can process more clients without upgrading hardware.
Although caching is a good thing, you must ensure that the client always runs the latest version of the application. When you deploy the next version of the website, you do not want the client to use outdated cached files.
Solution:
To ensure that you always use the latest file version, you must provide a unique URL for each file version. There are many strategies:
- Use query string: http://sample.com/file.js? V = 123
- Rename file: http://sample.com/file.123.js
- Create a directory: http://sample.com/123/file.js
ASP. NET Core provides a mechanism to append versions and query strings using TagHelper. It supports the most common HTML tags targeting static resources: script, link, and img. All you need to do is to append the object to the corresponding Html Tag.asp-append-version="true"
:
<link rel="stylesheet" href="~/css/site.css" rel="external nofollow" asp-append-version="true" /><script src="~/js/site.js" asp-append-version="true"></script>
Display in the browser:
<link rel="stylesheet" href="/css/site.css?v=1wp5zz4e-mOPFx4X2O8seW_DmUtePn5xFJk1vB7JKRc" rel="external nofollow" /><script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script>
Each file has a corresponding V value and is stored in an IMemoryCache.
The File URL is now unique and will be changed when the file is changed, so we can add the cache header to the response to indicate that the client files can be permanently stored in the cache
Practice
To instruct the browser to store files in the Cache, we must send the Cache-control header file and the Expires header file to achieve HTTP/1.0 compatibility. To add these header files, we use the OnPrepareResponse callback function StaticFilesOptions. Let's modify the Startup. cs file:
Public void Configure (IApplicationBuilder app, IHostingEnvironment env) {app. UseStaticFiles (new StaticFileOptions {OnPrepareResponse = context = >{// cache for one year if (! String. isNullOrEmpty (context. context. request. query ["v"]) {context. context. response. headers. add ("cache-control", new [] {"public, max-age = 31536000"}); context. context. response. headers. add ("Expires", new [] {DateTime. utcNow. addYears (1 ). toString ("R")}); // Format RFC1123 }}); app. useMvc (routes => {routes. mapRoute (name: "default", template: "{controller = Home}/{action = Index}/{id ?} ");});}
You can view the developer console and find that all static resources are cached:
If you do not want to cache a static file, modify the Startup. cs file:
App. UseStaticFiles (new StaticFileOptions {OnPrepareResponse = context =>{// cache for one year // The following operations are performed by default in UseStaticFiles if (! String. isNullOrEmpty (context. context. request. query ["v"]) // after adding asp-append-version = "true" to the resource, v is the Query parameter {// context. context. response. headers. add ("cache-control", new [] {"public, max-age = 31536000"}); context. context. response. headers. add ("cache-control", new [] {"public, no-cache"}); context. context. response. headers. add ("Expires", new [] {DateTime. utcNow. addYears (1 ). toString ("R")}); // Format RFC1123 }}});
Will you find that no matter how refresh, site. js? V = 7mkNbU1tgQL1bUeZe3j2R151hKLhLDKO4BBaR-iqCy0 files are always re-requested, and no cache mechanism is used
Conclusion
Using HTTP cache is important for performance reasons (client and server. With ASP. NET Core, you can use the provided TagHelpers function to generate a version control URL and change the default configuration StaticFilesMiddleware to add the Cache-control attribute of the header to the resource URL.
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.