写在前面

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

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

先看效果

ASP.NET MVC 扩展HtmlHelper类为 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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-03-04
  • 2021-12-17
  • 2021-08-07
  • 2021-06-21
  • 2022-02-22
  • 2021-10-26
猜你喜欢
  • 2021-07-30
  • 2021-10-24
  • 2021-06-27
  • 2021-05-18
  • 2021-07-15
  • 2021-08-01
相关资源
相似解决方案