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>

效果:

ASP.net Core MVC项目给js文件添加版本号

备注:刷新页面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中使用

@section pageScript
{
    <script src=@Context.AddFileVersionToPath("/Scripts/Common/DataEnum.js")></script>

效果

ASP.net Core MVC项目给js文件添加版本号