How to cache the NET core static files

Source: Internet
Author: User
Tags set time browser cache

How to cache the NET core static files

Read Catalogue

    • First, preface
    • Second, Staticfilemiddleware
    • ASP. NET Core and CDN?
    • Four, written in the last
Back to catalogue one, preface

When we optimize Web services , for static resource files , usually through the client cache , server cache ,CDN Cache , There are three ways to mitigate the stress of a client's connection request to a Web server.

This paper describes the implementation of static files in ASP. Three, and how to use them. Of course, you can also consider the use of reverse proxies (for example, IIS or Nginx), which are not what this article discusses.

This article focuses on how to improve the performance of the website through staticfilemiddleware middleware. While this is not the only way to cache files, we can also cache settings for the Controller and Action of ASP. NET Core MVC through the responsecacheattribute feature.

Back to catalogue two, Staticfilemiddleware 1. File services and default cache rules

When you create an ASP. NET core project, look at the Startup.configure method and see the default template-generated method for adding staticfilemiddleware middleware.

  1. Public void Configure(iapplicationbuilder app)
  2. {
  3. // looging and exception handler removed for clarity
  4. App. Usestaticfiles();
  5. App. Usemvc(routes =
  6. {
  7. Routes. MapRoute(
  8. Name: "default",
  9. template: "{controller=home}/{action=index}/{id?} ");
  10. });
  11. }

This allows your application to handle the static file contents of the wwwroot directory under the program directory. Before we add the file cache, let's take a look at staticfilemiddleware 's default policy. When the program is loaded for the first time, the browser opens the page and downloads all the resource connections. If the page does not return the error is correct then it is the status of return file data and HTTP status 200-ok.

We then look at the response Header for this HTTP request, which will contain the ETag and last-modified two values. The HTTP content is as follows:

  1. HTTP/1.1 OK
  2. Date: Sat, Oct :: GMT
  3. Content-Type: image/svg+XML
  4. Last-Modified: Sat, Oct : GMT
  5. Accept-Ranges: bytes
  6. ETag: "1d226ea1f827703"
  7. Server: Kestrel

If you request this address again, the browser will send the ETag and last-modified value to the server, if the two values do not change, then the server will send 304 status to the browser, Then the browser will use the previous resource instead of downloading a copy again.

This improves the responsiveness of the browser because the files are cached to the client, and the request traffic from the server and the browser is reduced through the 304 state.

2. Set the file cache time

Of course, we all know. If you want to set a cache for a request, you only need to set the value of the header to Cache-control . So in staticfilemiddleware middleware, how do we set this header?

  1. Using Microsoft. Net. Http. Headers;
  2. App. Usestaticfiles(new staticfileoptions
  3. {
  4. onprepareresponse = ctx + =
  5. {
  6. const int durationinseconds = * * ;
  7. CTX. Context. Response. Headers[headernames. CacheControl] =
  8. "public,max-age=" + durationinseconds;
  9. }
  10. });

The request for each static file is set to execute this method, including requests for 200 and 304 states , and in this case the browser automatically caches the files for 24 hours, but does not return 404 status during this time.

Once the Max-age set time expires, the browser will no longer use the local cache and go directly to the server side. This avoids some additional requests to the server side. If we use CDN cache file data in the middle of the browser and server, so that the client browser cache expires, but the request will not go to our server, but request to the CDN cache server.

Let's take a look at how the file cache in ASP. NET core Determines if the cache is invalidated. The. The core code is as follows:

  1. _length = _fileinfo. Length;
  2. DateTimeOffset last = _fileinfo. LastModified;
  3. Truncate to the second.
  4. _lastmodified= New DateTimeOffset(Lastyear, last. Month, last. Day, last. Hour, last. Minute, last. Second, last. Offsettouniversaltime ()
  5. long Etaghash = _ Lastmodified. Tofiletime () ^ _length ;
  6. _etag = new entitytagheadervalue('\ "' + Convert. ToString(etaghash, +) + '\ ');

Server side if detected file changes will return 200 status to the browser, if there is no change then return 304 status to the browser side.

Unfortunately, once we add the cache, the browser will no longer make a request to the server. The file may have been completely altered or has been completely removed, but if the browser is not required, the server will not be able to notify the browser to re-initiate a no-cache request!

3. Provide a version number for a static file

Usually we use addresses like https://localhost/js/site.js?v=1 to solve the problem of caching. By generating a unique version number for a static file, the server will re-export the contents of the file when requested for QueryString.

in ASP. Tag Hepers provides us with such an API:

    1. <script src="~/js/site.js" asp-append-version="true" ></script>

This code will eventually be rendered as the following HTML code on the browser side:

    1. <script src="/js/site.js?v=ynfdc1vumnowzfqtj4n3spcebazogxiipgtfe-b2to4"></ script>

If a static file changes, the Tag helper recalculates the hash of the file, which takes the hash value of the SHA256. Of course, the file version of the server cache has been invalidated before. This asp-append-version Tag Helper can support IMG, script, and link elements.

The source code of the ASP. We'll see how the file changes:source Codes .

Back to catalog three, ASP. NET Core and CDN?

When we use the CDN, because we have to carry out development tasks, we usually have two sets of addresses, one set is the CDN file address, a set of local debugging and development with the address. The tag helper is also available in the ASP. NET core to solve this problem. Go directly to the code example:

  1. <link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/ Bootstrap/3.0.0/css/bootstrap.min.css"
  2. asp-fallback-href="~/lib/bootstrap/css/bootstrap.min.css"
  3. ASP-fallback-test-class="hidden"
  4. asp-fallback-test-property="visibility"
  5. asp-fallback-test-value="hidden" />
  6. <script src="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/bootstrap.min.js"
  7. asp-fallback-src="~/lib/bootstrap/js/bootstrap.min.js"
  8. asp-fallback-test="window.jquery">
  9. </script>

Tag Helper:asp-fallback-* solves the problem of file address used during development. Of course it can also be used asp-append-version two tag helper together, so that the synchronization problem in CDN file cache is realized.

Back to table four, written in the last

The new ASP. NET core gives us a lot of solutions for the existing Internet industry, as well as. NET developers have introduced advanced ideas.

GITHUB:HTTPS://GITHUB.COM/MAXZHANG1985/YOYOFX If you feel you can also invite the Star , Welcome to communicate together.

Communication groups for. NET Core and YOYOFX: 214741894

How to cache the NET core static files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.