• ASP.NET MVC 扩展HtmlHelper类为 js ,css 资源文件添加版本号


    写在前面

    在项目部署当中会需要更新 css 文件或 js 等资源文件,为了避免由于浏览器缓存的原因无法加载新的 css 或 js ,一般的做法是在资源文件的后面加上一个版本号来解决,这样浏览器就会去服务器下载新的资源文件。

    如果某个 css 文件被多个页面引用,那么我们就需要去每个页面一个一个的去修改,这样做的方式属于重复性的动作,而且有的时候还会漏掉需要修改的页面,所以我们就需要一个自动管理资源文件版本号的功能

    先看效果

    如何实现

    通过扩展HemHelper 类,添加 为 js 和 css 文件处理的方法

    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 hashValue = VersionUtils.GetFileVersion(httpContenxt.Server.MapPath(contentPath));
                contentPath = UrlHelper.GenerateContentUrl(contentPath, httpContenxt) + "?v=" + hashValue;
                return MvcHtmlString.Create(string.Format(template, contentPath));
            }
    
        }
    View Code

     新建一个 VersionUtils 类来生成资源文件的版本号,下面的代码实现了计算文件的 hash 值作为版本号

    public static class VersionUtils
        {
            public static Dictionary<string, string> FileHashDic = new Dictionary<string, string>();
            public static string GetFileVersion(string filePath)
            {
                /*
                 * 生成版本号有三种方式
                 * 1. 将文件的将最后一次写入时间作为版本号 => File.GetLastWriteTime(filePath).ToString("yyyyMMddHHmmss");
                 * 2. 从配置文件中读取预先设定版本号  => ConfigurationManager.AppSettings["Js_CSS_Version"];
                 * 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;
            }
        }

    如何使用

    在View中的使用方式

    @Html.Style("~/Content/table.css")
    @Html.Style("~/Content/wxSite.css")
    @Html.Script("~/Scripts/jquery-1.10.2.min.js")

    参考文章

    https://www.cnblogs.com/aehyok/archive/2012/11/17/2774500.html

  • 相关阅读:
    Apache Hive (三)Hive元数据信息对应MySQL数据库表
    Apache Hive (二)Hive安装
    Apache Hive (一)Hive初识
    C#使用NPOI导出excel设置单元格背景颜色
    Spark之 Spark Streaming整合kafka(并演示reduceByKeyAndWindow、updateStateByKey算子使用)
    Spark之 Spark Streaming流式处理
    Apache Flume的介绍安装及简单案例
    Kafka如何保证数据不丢失
    Ajax
    HttpComponents
  • 原文地址:https://www.cnblogs.com/wubh/p/9512391.html
Copyright © 2020-2023  润新知