写在前面
在项目部署当中会需要更新 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)); } }