ASP.NET MVC捆绑缓存.(检测css文件更改)(内部行为)

Aga*_*gat 16 css asp.net-mvc bundle

我一直在深入研究ASP.NET MVC内部功能(不同的原因),但仍然无法涵盖所有​​行为.其中一个我没有的是subj.

它的工作方式如下:

如果我捆绑一些文件(例如css文件),框架会检测这些更改并为新包生成新的id(以便浏览器轻松刷新更改),例如href ="/ Content/css?v = qartPE4jGe- l1U0I7kNDZPZzVTdh0kT8VBZZA_uURjI1" .

我实际上想要了解的内容:

  1. 框架(可能不是MVC但是.NET的东西)究竟是如何检测到文件被更改的(因为没有目录观察者活动(因为我可以更改文件,即使在离线时也可以更改文件)以查看文件更改实时,并且系统实际上检测到文件内容发生了变化(我尝试重新保存文件而不更改其内容,并且捆绑编号也没有改变))?(我认为显然系统无法比较每个文件内容以检测每个请求的变化).

  2. 框架存储当前包ID的位置(以及如何)以及它如何存储以前的版本(因为以前的包在转到其URL时仍然可用)?

非常感谢!

Ben*_*ter 14

ASP.NET优化框架将bundle响应缓存在其中,HttpContext.Cache并使用CacheDependency监视bundle中的每个文件以进行更改.这就是直接更新文件使缓存无效并重新生成包的原因.

捆绑包文件名是捆绑包内容的散列,可确保在修改任何捆绑包文件时更改URL.bundle的虚拟路径用作缓存键.

来自库的相关代码(请注意,这稍微过时,但我相信逻辑仍然相同):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,对于旧的捆绑URL工作,我认为你会发现它们要么从浏览器缓存返回,要么实际返回最新版本的捆绑包,因为捆绑路径不会改变,只有版本查询字符串.

  • 好吧,谢谢你的答案,但对我来说仍然听起来像:"它只是使用缓存".好吧,我确信它使用缓存(这是web(以及许多其他)技术的工作方式),但我的问题是实用的(不只是一些理论,捆绑的类或模块):它是要理解是否页面渲染会检查每个Web请求的文件更改(来自bundle文件)吗?或不?如果没有,那么(奇怪/理论上)它监测这些变化的确切方式是什么? (2认同)