The static file caching method of ASP. NET Core, asp. netcore

Source: Internet
Author: User
Tags website performance

The static file caching method of ASP. NET Core, asp. netcore
I. Preface

InOptimize Web ServicesForStatic resource files, Usually throughClient Cache,Server Cache,CDN CacheThese three methods are used to relieve the client's pressure on connecting requests to the Web server.

This article describes the implementation process and usage of static files in ASP. NET Core. Of course, you can also consider using reverse proxy (such as IIS or Nginx), which is not discussed in this article.

This article focuses on how to useStaticFileMiddlewareMiddleware to improve website performance. Although this is not the only way to cache files, we can also useResponseCacheAttributeThe feature is the Controller and Action of ASP. NET Core Mvc for cache settings.

Ii. StaticFileMiddleware 1. File Service and default cache rules

When you create an ASP. NET Core project, view the Startup. Configure method and you will see the addition of the default template.StaticFileMiddlewareMiddleware method.

public void Configure(IApplicationBuilder app)  {    // looging and exception handler removed for clarity    app.UseStaticFiles();    app.UseMvc(routes =>    {        routes.MapRoute(            name: "default",            template: "{controller=Home}/{action=Index}/{id?}");    });}

In this way, your application can be processed.Wwwroot directory. Before we add a File Cache, let's take a look.StaticFileMiddlewareWhat is the Default policy. When a program is loaded for the first time, the browser opens the page and downloads all resource connections. If no error is returned on the page, the system returns the file data and the Http Status is 200-OK.

 

Next, let's take a look at the Response Header corresponding to this Http request, which will includeETagAndLast-ModifiedTwo values. The HTTP content is as follows:

HTTP/1.1 200 OK  Date: Sat, 15 Oct 2016 14:15:52 GMT  Content-Type: image/svg+xml  Last-Modified: Sat, 15 Oct 2016 13:43:34 GMT  Accept-Ranges: bytes  ETag: "1d226ea1f827703"  Server: Kestrel  

If you request this address again, the browser will sendETagAndLast-ModifiedIf the two values are not changed, the server sends304Status to the browser, the browser will use the previous resources instead of downloading them again.

This improves the browser's response performance, because the files are cached on the client, and the request traffic between the server and the browser is reduced through the 304 status.

2. Set the File Cache Time

Of course, we all know that to set the cache of a request, you only need to set the HeaderCache-Control. InStaticFileMiddlewareIn middleware, how do we set this Header?

using Microsoft.Net.Http.Headers;app.UseStaticFiles(new StaticFileOptions  {    OnPrepareResponse = ctx =>    {        const int durationInSeconds = 60 * 60 * 24;        ctx.Context.Response.Headers[HeaderNames.CacheControl] =            "public,max-age=" + durationInSeconds;    }});

 

This method will be executed for every request to a static file after the setting,Requests in the 200 and 304 statusesIn this example, the browser automatically caches these files for 24 hours.Status 404 is not returned.

OnceMax-ageWhen the set time expires, the browser will not use the local cache, but directly request the server. This avoids some additional requests to the server. If we use CDN to cache file data between the browser and the server, even if the client browser's cache expires, the request will not go to our server, but will go to the CDN cache server.

Next, let's take a look at how files are cached in ASP. NET Core to determine that the cache is invalid ?. NET Core open-source code provides us with an entry to understand it[Code Source Code]. The core code is as follows:

_length = _fileInfo.Length;DateTimeOffset last = _fileInfo.LastModified;  // Truncate to the second._lastModified = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, last.Offset).ToUniversalTime();long etagHash = _lastModified.ToFileTime() ^ _length;  _etag = new EntityTagHeaderValue('\"' + Convert.ToString(etagHash, 16) + '\"'); 

If the server detects a file change, the server returns the 200 status to the browser. If the file does not change, the server returns the 304 status to the browser.

Unfortunately, once we add a cache, the browser will no longer send requests to the server. This file may have been completely changed or deleted. However, if the browser does not require this file, the server will not be able to notify the browser to initiate a cache-free request again!

3. Provide the version number for the static file

Usually we use https: // localhost/js/site. js? Address v = 1 to solve the cache problem. By generating a unique version number for the static file, the server will output the file content again when making a request as QueryString.

In ASP. NET Core, Tag Hepers provides the following APIs:

<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:

<script src="/js/site.js?v=Ynfdc1vuMNOWZfqTj4N3SPcebazoGXiIPgtfE-b2TO4"></script> 

If the static file changes, Tag Helper re-calculates the file hash value, which uses the SHA256 hash value. Of course, the file version cached on the server also becomes invalid. ThisAsp-append-versionTag Helper supports Img, Script, and Link elements.

The source code of ASP. NET Core is used to calculate the file changes:[Source Code].

Iii. ASP. NET Core and CDN?

When using CDN, we usually have two sets of addresses, one for the file address on CDN and the other for local debugging and development. ASP. NET Core also provides Tag Helper for us to solve this problem. Go directly to the Code instance:

<link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/css/bootstrap.min.css"      asp-fallback-href="~/lib/bootstrap/css/bootstrap.min.css"      asp-fallback-test-class="hidden"       asp-fallback-test-property="visibility"       asp-fallback-test-value="hidden" /><script src="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/bootstrap.min.js"        asp-fallback-src="~/lib/bootstrap/js/bootstrap.min.js"        asp-fallback-test="window.jQuery"></script>

Tag Helper:Asp-fallback -*Solve the Problem of file addresses used during development. Of course, it does.Asp-append-versionThe two tags Helper are used together to implement the synchronization problem in the CDN File Cache.

4. Write at the end

The new ASP. NET Core provides us with a lot of existing Internet industry solutions and introduces advanced ideas to. NET developers.

 

GitHub: https://github.com/maxzhang1985/YOYOFx if you feel OKStar.

. NET Core and YOYOFx exchange group:214741894

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

Related Article

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.