在项目部署当中会须要更新 css 文件或 js 等资源文件,为了不因为浏览器缓存的缘由没法加载新的 css 或 js ,通常的作法是在资源文件的后面加上一个版本号来解决,这样浏览器就会去服务器下载新的资源文件。javascript
若是某个 css 文件被多个页面引用,那么咱们就须要去每一个页面一个一个的去修改,这样作的方式属于重复性的动做,并且有的时候还会漏掉须要修改的页面,因此咱们就须要一个自动管理资源文件版本号的功能css
经过扩展HemHelper 类,添加 为 js 和 css 文件处理的方法html
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)); } }
新建一个 VersionUtils 类来生成资源文件的版本号,下面的代码实现了计算文件的 hash 值做为版本号java
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中的使用方式jquery
@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数组