How to force BundleCollection to flush cached script bundles in MVC4

前端 未结 6 1352
梦谈多话
梦谈多话 2020-11-29 19:28

... or how I learned to stop worrying and just write code against completely undocumented APIs from Microsoft. Is there any actual documentation of the official

6条回答
  •  独厮守ぢ
    2020-11-29 19:42

    I also ran into issues with updating bundles without rebuilding. Here are the important things to understand:

    • The bundle DOES NOT get updated if the file paths change.
    • The bundle DOES get updated if the bundle's virtual path changes.
    • The bundle DOES get updated if the files on disk change.

    So knowing that, if you're doing dynamic bundling, you can write some code to make the bundle's virtual path be based on the file paths. I recommend hashing the file paths and appending that hash to the end of the bundle's virtual path. This way when the file paths change so does the virtual path and the bundle will update.

    Here's the code I ended up with that solved the issue for me:

        public static IHtmlString RenderStyleBundle(string bundlePath, string[] filePaths)
        {
            // Add a hash of the files onto the path to ensure that the filepaths have not changed.
            bundlePath = string.Format("{0}{1}", bundlePath, GetBundleHashForFiles(filePaths));
    
            var bundleIsRegistered = BundleTable
                .Bundles
                .GetRegisteredBundles()
                .Where(bundle => bundle.Path == bundlePath)
                .Any();
    
            if(!bundleIsRegistered)
            {
                var bundle = new StyleBundle(bundlePath);
                bundle.Include(filePaths);
                BundleTable.Bundles.Add(bundle);
            }
    
            return Styles.Render(bundlePath);
        }
    
        static string GetBundleHashForFiles(IEnumerable filePaths)
        {
            // Create a unique hash for this set of files
            var aggregatedPaths = filePaths.Aggregate((pathString, next) => pathString + next);
            var Md5 = MD5.Create();
            var encodedPaths = Encoding.UTF8.GetBytes(aggregatedPaths);
            var hash = Md5.ComputeHash(encodedPaths);
            var bundlePath = hash.Aggregate(string.Empty, (hashString, next) => string.Format("{0}{1:x2}", hashString, next));
            return bundlePath;
        }
    

提交回复
热议问题