Auto-versioning in ASP.NET MVC for CSS / JS Files?

前端 未结 4 968
礼貌的吻别
礼貌的吻别 2020-12-08 00:09

I have read lots of article on how to auto-version your CSS/JS files - but none of these really provide an elegant way to do this in ASP.NET MVC.

This link - How to

4条回答
  •  执念已碎
    2020-12-08 00:40

    When faced with this problem I wrote a series of wrapper functions around the UrlHelper's Content method:

    EDIT:

    Following the discussions in the comments below I updated this code:

    public static class UrlHelperExtensions
    {
        private readonly static string _version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
    
        private static string GetAssetsRoot()
        {
            string root = ConfigurationManager.AppSettings["AssetsRoot"];
            return root.IsNullOrEmpty() ? "~" : root;
        }
    
        public static string Image(this UrlHelper helper, string fileName)
        {
            return helper.Content(string.Format("{0}/v{2}/assets/img/{1}", GetAssetsRoot(), fileName, _version));
        }
    
        public static string Asset(this UrlHelper helper, string fileName)
        {
            return helper.Content(string.Format("{0}/v{2}/assets/{1}", GetAssetsRoot(), fileName, _version));
        }
    
        public static string Stylesheet(this UrlHelper helper, string fileName)
        {
            return helper.Content(string.Format("{0}/v{2}/assets/css/{1}", GetAssetsRoot(), fileName, _version));
        }
    
        public static string Script(this UrlHelper helper, string fileName)
        {
            return helper.Content(string.Format("{0}/v{2}/assets/js/{1}", GetAssetsRoot(), fileName, _version));
        }
    }
    

    Using these functions in conjunction with the following rewrite rule should work:

    
      
        
          
          
        
      
    
    

    This article discusses how to create rewrite rules on IIS7.

    This code uses the version number of the current assembly as a query string parameter on the file path's it emits. When I do an update to the site and the build number increments, so does the querystring parameter on the file, and so the user agent will re-download the file.

提交回复
热议问题