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

应用场景:

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

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

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

1、效果如下:

ASP .NET MVC 自动为js ,css等文件添加版本号_第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 
{
    /// 
    /// created by 墨染子柒
    /// 2019.12.02
    /// 
    public static class HtmlHelperExtension
    {
        /// 
        /// 自动为 Js 文件添加版本号
        /// 
        /// 
        /// 
        /// 
        public static MvcHtmlString Script(this HtmlHelper html, string contentPath)
        {
            return VersionContent(html, "", contentPath);
        }
        /// 
        /// 自动为 css 文件添加版本号
        /// 
        /// 
        /// 
        /// 
        public static MvcHtmlString Style(this HtmlHelper html, string contentPath)
        {
            return VersionContent(html, "", 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 FileHashDic = new Dictionary();
        public static string GetFileVersion(string filePath)
        {
            /*
             * 生成版本号有三种方式
             * 1. 将文件的将最后一次写入时间作为版本号
             * 2. 从配置文件中读取预先设定版本号
             * 3. 计算文件的 hash 值  
             */

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

            //2、从配置文件中读取预先设定版本号
            //web.config中添加一下代码:
            //
            //
            //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


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

你可能感兴趣的:(Asp.Net)