javascript版本(asp-append-version)如何在ASP.NET Core MVC中工作

似乎新的MVC( 链接 )中不支持动态捆绑,应该使用gulp任务来完成。 MVC支持一些名为asp-append-version新属性,但我没有找到有关它如何工作的任何解释。 我怀疑它正在计算文件内容的一些哈希值,甚至在文件更改后更新它。 有没有关于它是如何工作的文件?

我也想知道它是如何检测文件更改或者它是否只是每次MVC解析剃刀标记时重新计算哈希值。

您可以查看LinkTagHelper源代码,您将看到它基本上是通过FileVersionProvider将版本查询字符串添加到href值:

 if (AppendVersion == true) { EnsureFileVersionProvider(); if (Href != null) { output.Attributes[HrefAttributeName].Value = _fileVersionProvider.AddFileVersionToPath(Href); } } private void EnsureFileVersionProvider() { if (_fileVersionProvider == null) { _fileVersionProvider = new FileVersionProvider( HostingEnvironment.WebRootFileProvider, Cache, ViewContext.HttpContext.Request.PathBase); } } 

FileVersionProvider使用SHA256算法计算文件内容的哈希值 。 然后它将对其进行url编码并将其添加到查询字符串中,如下所示:

 path/to/file?v=B95ZXzHiOuQJzhBoHlSlNyN1_cOjJnz2DFsr-3ZyyJs 

只有在文件更改时才会重新计算哈希值 ,因为它会添加到缓存中,但具有基于文件观察程序的过期触发器:

 if (!_cache.TryGetValue(path, out value)) { value = QueryHelpers.AddQueryString(path, VersionKey, GetHashForFile(fileInfo)); var cacheEntryOptions = new MemoryCacheEntryOptions().AddExpirationToken(_fileProvider.Watch(resolvedPath)); _cache.Set(path, value, cacheEntryOptions); } 

这个观察者由HostingEnvironment.WebRootFileProvider提供,它实现了IFileProvider

 // // Summary: // Creates a change trigger with the specified filter. // // Parameters: // filter: // Filter string used to determine what files or folders to monitor. Example: **/*.cs, // *.*, subFolder/**/*.cshtml. // // Returns: // An Microsoft.Framework.Caching.IExpirationTrigger that is triggered when a file // matching filter is added, modified or deleted. IExpirationTrigger Watch(string filter); 

注意:您可以通过检查IMemoryCache中的值来自己查看缓存的值:

 //give the link:  //You can check the cached version this.Context.RequestServices.GetRequiredService().Get("/css/site.css") //Which will show a value like: /css/site.css?v=B95ZXzHiOuQJzhBoHlSlNyN1_cOjJnz2DFsr-3ZyyJs 

在剃刀

 var fileversion = '@this.AddFileVersionToPath("/js/components/forms.js")'; 

扩展方法

 using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.TagHelpers.Internal; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; public static class IRazorPageExtensions { public static string AddFileVersionToPath(this IRazorPage page, string path) { var context = page.ViewContext.HttpContext; IMemoryCache cache = context.RequestServices.GetRequiredService(); var hostingEnvironment = context.RequestServices.GetRequiredService(); var versionProvider = new FileVersionProvider(hostingEnvironment.WebRootFileProvider, cache, context.Request.Path); return versionProvider.AddFileVersionToPath(path); } } 

根据FileVersionProvider的当前实现,hash仅添加到相对文件路径,例如以防万一使用绝对路径,例如https://code.jquery.com/jquery-3.1.1.js ,不会添加哈希。