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

后端 未结 6 1523
不思量自难忘°
不思量自难忘° 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:41

    You just need a unique string. It doesn't have to be Hash. We use the LastModified date of the file and get the Ticks from there. Opening and reading the file is expensive as @Todd noted. Ticks is enough to output a unique number that changes when the file is changed.

    internal static class BundleExtensions
    {
        public static Bundle WithLastModifiedToken(this Bundle sb)
        {
            sb.Transforms.Add(new LastModifiedBundleTransform());
            return sb;
        }
        public class LastModifiedBundleTransform : IBundleTransform
        {
            public void Process(BundleContext context, BundleResponse response)
            {
                foreach (var file in response.Files)
                {
                    var lastWrite = File.GetLastWriteTime(HostingEnvironment.MapPath(file.IncludedVirtualPath)).Ticks.ToString();
                    file.IncludedVirtualPath = string.Concat(file.IncludedVirtualPath, "?v=", lastWrite);
                }
            }
        }
    }
    

    and how to use it:

    bundles.Add(new StyleBundle("~/bundles/css")
        .Include("~/Content/*.css")
        .WithLastModifiedToken());
    

    and this is what MVC writes:

    
    

    works fine with Script bundles too.

提交回复
热议问题