MVC4 StyleBundle: Can you add a cache-busting query string in Debug mode?

后端 未结 6 1533
不思量自难忘°
不思量自难忘° 2020-12-13 06:16

I\'ve got an MVC application and I\'m using the StyleBundle class for rendering out CSS files like this:

bundles.Add(new StyleBundle(\"~/bundles         


        
6条回答
  •  盖世英雄少女心
    2020-12-13 06:45

    You can create a custom IBundleTransform class to do this. Here's an example that will append a v=[filehash] parameter using a hash of the file contents.

    public class FileHashVersionBundleTransform: IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse response)
        {
            foreach(var file in response.Files)
            {
                using(FileStream fs = File.OpenRead(HostingEnvironment.MapPath(file.IncludedVirtualPath)))
                {
                    //get hash of file contents
                    byte[] fileHash = new SHA256Managed().ComputeHash(fs);
    
                    //encode file hash as a query string param
                    string version = HttpServerUtility.UrlTokenEncode(fileHash);
                    file.IncludedVirtualPath = string.Concat(file.IncludedVirtualPath, "?v=", version);
                }                
            }
        }
    }
    

    You can then register the class by adding it to the Transforms collection of your bundles.

    new StyleBundle("...").Transforms.Add(new FileHashVersionBundleTransform());
    

    Now the version number will only change if the file contents change.

提交回复
热议问题