找人做网站需要先了解哪些要点,创意网站建设价格多少,和淘宝同时做电商的网站,做视频网站是什么职业写在前面 在项目部署当中会需要更新 css 文件或 js 等资源文件#xff0c;为了避免由于浏览器缓存的原因无法加载新的 css 或 js #xff0c;一般的做法是在资源文件的后面加上一个版本号来解决#xff0c;这样浏览器就会去服务器下载新的资源文件。 如果某个 css 文件被多个… 写在前面 在项目部署当中会需要更新 css 文件或 js 等资源文件为了避免由于浏览器缓存的原因无法加载新的 css 或 js 一般的做法是在资源文件的后面加上一个版本号来解决这样浏览器就会去服务器下载新的资源文件。 如果某个 css 文件被多个页面引用那么我们就需要去每个页面一个一个的去修改这样做的方式属于重复性的动作而且有的时候还会漏掉需要修改的页面所以我们就需要一个自动管理资源文件版本号的功能 先看效果 如何实现 通过扩展HemHelper 类添加 为 js 和 css 文件处理的方法 public static class HtmlHelperExtension{/// summary/// 自动为 Js 文件添加版本号/// /summary/// param namehtml/param/// param namecontentPath/param/// returns/returnspublic static MvcHtmlString Script(this HtmlHelper html, string contentPath){return VersionContent(html, script src\{0}\ type\text/javascript\/script, contentPath);}/// summary/// 自动为 css 文件添加版本号/// /summary/// param namehtml/param/// param namecontentPath/param/// returns/returnspublic 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 Dictionarystring, string FileHashDic new Dictionarystring, 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 转载于:https://www.cnblogs.com/wubh/p/9512391.html