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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM