ASP .NET MVC 自动为js ,css等文件添加版本号

应用场景:

在项目部署中,更新 css 或 js 等资源文件时,为了避免由于浏览器缓存的原因,导致客户端无法加载最新的 css 或 js ,一般会在资源文件的后面加上一个版本号来解决(例如:main.js?v=1.0.0),这样浏览器就会请求服务器下载新的资源文件。

如果某个 css/js 文件被多个页面引用,或者有一大批css/js文件需要更新,那么我们就需要在每个引用的地方都加上版本号。这样做的方式属于重复性的动作,有的时候还会漏掉需要修改的页面,而且不便于版本的更新。

所以我们就需要一个自动管理资源文件版本号的功能。

1、效果如下:

 2、实现方法

通过扩展HemHelper 类,添加处理js和css等文件的方法(相关注释已包含在代码中)
介绍三种方法:
       * 1. 将文件的将最后一次写入时间作为版本号
       * 2. 从配置文件中读取预先设定版本号
       * 3. 计算文件的 hash 值  

个人推荐第一种,简洁明了,易于理解。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;

namespace System.Web.Mvc 
{
    /// <summary>
    /// created by 墨染子柒
    /// 2019.12.02
    /// </summary>
    public static class HtmlHelperExtension
    {
        /// <summary>
        /// 自动为 Js 文件添加版本号
        /// </summary>
        /// <param name="html"></param>
        /// <param name="contentPath"></param>
        /// <returns></returns>
        public static MvcHtmlString Script(this HtmlHelper html, string contentPath)
        {
            return VersionContent(html, "<script src=\"{0}\" type=\"text/javascript\"></script>", contentPath);
        }
        /// <summary>
        /// 自动为 css 文件添加版本号
        /// </summary>
        /// <param name="html"></param>
        /// <param name="contentPath"></param>
        /// <returns></returns>
        public static MvcHtmlString Style(this HtmlHelper html, string contentPath)
        {
            return VersionContent(html, "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\">", contentPath);
        }

        private static MvcHtmlString VersionContent(this HtmlHelper html, string template, string contentPath)
        {
            var httpContenxt = html.ViewContext.HttpContext;
            //获取版本号
            string Value = VersionUtils.GetFileVersion(httpContenxt.Server.MapPath(contentPath));
            contentPath = UrlHelper.GenerateContentUrl(contentPath, httpContenxt) + "?v=" + Value;
            return MvcHtmlString.Create(string.Format(template, contentPath));
        }

    }
    public static class VersionUtils
    {
        public static Dictionary<string, string> FileHashDic = new Dictionary<string, string>();
        public static string GetFileVersion(string filePath)
        {
            /*
             * 生成版本号有三种方式
             * 1. 将文件的将最后一次写入时间作为版本号
             * 2. 从配置文件中读取预先设定版本号
             * 3. 计算文件的 hash 值  
             */

            //1、直接读取修改时间作为版本号
            return File.GetLastWriteTime(filePath).ToString("yyyyMMddHHmmss");

            //2、从配置文件中读取预先设定版本号
            //web.config中添加一下代码:
            //<!--添加自定义版本号-->
            //<add key="JsCssVersion" value="20191202.1"/>
            //return ConfigurationManager.AppSettings["JsCssVersion"];

            //3、文件hash
            //string fileName = Path.GetFileName(filePath);
             验证是否已计算过文件的Hash值,避免重复计算
            //if (FileHashDic.ContainsKey(fileName))
            //{
            //    return FileHashDic[fileName];
            //}
            //else
            //{
            //    string hashvalue = GetFileShaHash(filePath); //计算文件的hash值
            //    FileHashDic.Add(fileName, hashvalue);
            //    return hashvalue;
            //}
        }

        private static string GetFileShaHash(string filePath)
        {
            string hashSHA1 = String.Empty;
            //检查文件是否存在,如果文件存在则进行计算,否则返回空值
            if (System.IO.File.Exists(filePath))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    //计算文件的SHA1值
                    System.Security.Cryptography.SHA1 calculator = System.Security.Cryptography.SHA1.Create();
                    Byte[] buffer = calculator.ComputeHash(fs);
                    calculator.Clear();
                    //将字节数组转换成十六进制的字符串形式
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < buffer.Length; i++)
                    {
                        stringBuilder.Append(buffer[i].ToString("x2"));
                    }
                    hashSHA1 = stringBuilder.ToString();
                }//关闭文件流
            }
            return hashSHA1;
        }
    }
}

3、页面调用方式 

@Html.Script("~/Content/Scripts/Business/Home/DemoTest.js")
@Html.Style("~/Content/Scripts/Business/Home/DemoTest.css")

4、 github地址如下:

https://github.com/736755244/HtmlHelperExtension


有相关问题,欢迎留言讨论!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值