ASP.NET MVC Bundling cache. (Detecting css files changes) (internal behaviour)

后端 未结 1 662
我寻月下人不归
我寻月下人不归 2020-12-18 21:10

I\'ve been diving into ASP.NET MVC internal functionality much (different reasons), but still can not cover all the behaviour. One of those which I did not is subj.

相关标签:
1条回答
  • 2020-12-18 21:45

    The ASP.NET Optimization framework caches the bundle response in HttpContext.Cache and uses a CacheDependency to monitor each file in the bundle for changes. This is why updating the files directly invalidates the cache and regenerates the bundle.

    The bundle file name is a hash of the bundle contents which ensures the URL changes when any of the bundle files are modified. The bundle's virtual path is used as the cache key.

    The relevant code from the library (note this is slightly out of date but I believe the logic is still the same):

    internal BundleResponse GetBundleResponse(BundleContext context)
    {
        // check to see if the bundle response is in the cache
        BundleResponse bundleResponse = Bundle.CacheLookup(context);
        if (bundleResponse == null || context.EnableInstrumentation)
        {
            // if not, generate the bundle response and cache it
            bundleResponse = this.GenerateBundleResponse(context);
            if (context.UseServerCache)
            {
                this.UpdateCache(context, bundleResponse);
            }
        }
        return bundleResponse;
    }
    
    private void UpdateCache(BundleContext context, BundleResponse response)
    {
        if (context.UseServerCache)
        {
            // create a list of all the file paths in the bundle
                List<string> list = new List<string>();
            list.AddRange(
                from f in response.Files
                select f.FullName);
            list.AddRange(context.CacheDependencyDirectories);
            string cacheKey = Bundle.GetCacheKey(context.BundleVirtualPath);
            // insert the response into the cache with a cache dependency that monitors
            // the bundle files for changes
            context.HttpContext.Cache.Insert(cacheKey, response, new CacheDependency(list.ToArray()));
            context.HttpContext.Response.AddCacheItemDependency(cacheKey);
            this._cacheKeys.Add(cacheKey);
        }
    }
    

    Finally as for old bundle URLs working, I think you will find they are either returned from your browser cache or actually return the latest version of the bundle since the bundle path doesn't change, only the version query string.

    0 讨论(0)
提交回复
热议问题