ASP.net Core MVC项目给js文件添加版本号
需求:使用ASP.net Core Mvc開發公司內部web系統,給視圖中js(css,image也可以)文件添加版本號避免緩存問題。
解決方法:利用Taghelper提供的標簽(asp-append-version)可以實現
<script src="~/Scripts/Biz/VillageResource/XXXX.js" asp-append-version="true"></script>效果:
備注:刷新頁面js版本號不會變化,直到變動js內容變化,版本號才會變化。下文根據源碼,了解asp-append-version是如何實現的。
if (AppendVersion == true){EnsureFileVersionProvider();if (Href != null){var index = output.Attributes.IndexOfName(HrefAttributeName);var existingAttribute = output.Attributes[index];output.Attributes[index] = new TagHelperAttribute(existingAttribute.Name,FileVersionProvider.AddFileVersionToPath(ViewContext.HttpContext.Request.PathBase, Href),existingAttribute.ValueStyle);}} private void EnsureFileVersionProvider(){if (FileVersionProvider == null){FileVersionProvider = ViewContext.HttpContext.RequestServices.GetRequiredService<IFileVersionProvider>();}}解析IFileVersionProvider的實現,然后調用AddFileVersionToPath方法添加版本號,AddFileVersionToPath源碼如下:
public string AddFileVersionToPath(PathString requestPathBase, string path){if (path == null){throw new ArgumentNullException(nameof(path));}var resolvedPath = path;var queryStringOrFragmentStartIndex = path.IndexOfAny(QueryStringAndFragmentTokens);if (queryStringOrFragmentStartIndex != -1){resolvedPath = path.Substring(0, queryStringOrFragmentStartIndex);}if (Uri.TryCreate(resolvedPath, UriKind.Absolute, out var uri) && !uri.IsFile){// Don't append version if the path is absolute.return path;}if (Cache.TryGetValue(path, out string value)){return value;}var cacheEntryOptions = new MemoryCacheEntryOptions();cacheEntryOptions.AddExpirationToken(FileProvider.Watch(resolvedPath));var fileInfo = FileProvider.GetFileInfo(resolvedPath);if (!fileInfo.Exists &&requestPathBase.HasValue &&resolvedPath.StartsWith(requestPathBase.Value, StringComparison.OrdinalIgnoreCase)){var requestPathBaseRelativePath = resolvedPath.Substring(requestPathBase.Value.Length);cacheEntryOptions.AddExpirationToken(FileProvider.Watch(requestPathBaseRelativePath));fileInfo = FileProvider.GetFileInfo(requestPathBaseRelativePath);}if (fileInfo.Exists){value = QueryHelpers.AddQueryString(path, VersionKey, GetHashForFile(fileInfo));}else{// if the file is not in the current server.value = path;}cacheEntryOptions.SetSize(value.Length * sizeof(char));value = Cache.Set(path, value, cacheEntryOptions);return value;}private static string GetHashForFile(IFileInfo fileInfo){using (var sha256 = CryptographyAlgorithms.CreateSHA256()){using (var readStream = fileInfo.CreateReadStream()){var hash = sha256.ComputeHash(readStream);return WebEncoders.Base64UrlEncode(hash);}}}通過AddFileVersionToPath源碼可以弄明白:
js版本號 如何實現的?
在GetHashForFile方法,根據文件的內容利用SHA256算法得到其hash值,然后通過url編碼得到js的版本號如:?v=b_XmH4_MtWTW4959ESAEqaO3-Tqh9QSlrJgwrQ1YplA
為什么更改了js文件內容,版本號會改變?
第一次得到版本號,會放入緩存中( value = Cache.Set(path, value, cacheEntryOptions);),同時緩存添加過期條件,判斷依據文件是否發生變化( cacheEntryOptions.AddExpirationToken(FileProvider.Watch(requestPathBaseRelativePath));),否-直接或從緩存中獲取。是-調用GetHashForFile方法重新生成。
動手添加個獲取版本號的擴展方法
public static class HttpContextExtends{public static string AddFileVersionToPath(this HttpContext context, string path){return context.RequestServices.GetRequiredService<IFileVersionProvider>().AddFileVersionToPath(context.Request.PathBase, path);}}view中使用
@p pageScript {<script src=@Context.AddFileVersionToPath("/Scripts/Common/DataEnum.js")></script>效果
總結
以上是生活随笔為你收集整理的ASP.net Core MVC项目给js文件添加版本号的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS Code 黑宝书背后的故事
- 下一篇: 初识ABP vNext(1):开篇计划基