href js改变link_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>

效果:

1348738b4d97d87f743159630f50a5b7.png

备注:刷新页面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的实现,然后调用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()
.AddFileVersionToPath(context.Request.PathBase, path);
}
}

view中使用

@section pageScript
{

效果

da3319e49926b768c560ba1c9e6e143d.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值