【问题标题】:Does MVC OutputCaching take preference over setting cache response headers?MVC OutputCaching 是否优先于设置缓存响应标头?
【发布时间】:2011-05-03 22:44:42
【问题描述】:

这个问题与my other question有关。

我有一个 MVC 应用程序,所有控制器操作都禁用了缓存。我通过在Application_BeginRequest 中设置缓存响应标头来做到这一点:

    protected void Application_BeginRequest()
    {
        HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
        HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
    }

我确实希望启用缓存的单个控制器操作。我用OutputCache 属性修饰了这个动作:

[OutputCache(Duration = 300, VaryByParam = "id")]

此操作现在会发生什么?是因为 OutputCache 属性而被缓存,还是因为响应头而没有被缓存?

-- 编辑--

看起来,响应标头优先。所以我的问题变成了:如何为单个控制器操作启用缓存?再次覆盖响应头?

【问题讨论】:

    标签: c# .net asp.net-mvc caching outputcache


    【解决方案1】:

    这两件事是分开的;响应缓存主要查看客户端看到的内容 - 他们将在不访问服务器的情况下使用什么,或者他们将发送到服务器的修改日期。 p>

    OutputCache,然而,专注于服务器;请求仍将发生(与客户端缓存的内容不同),但有可能(希望很可能)不会调用您的方法:相反,将返回缓存的版本。

    所以:它在客户端没有缓存;发出一个 HTTP 请求,并且(对于 5 分钟内的请求,对于相同的 id,内存允许)从服务器返回 cached 版本(通常减少服务器的 IO 和 CPU 负载) .有意义吗?

    【讨论】:

    • 这只是部分正确。 OutputCacheLocation.Any value from MSDN:“输出缓存可以位于浏览器客户端(发起请求的地方)、参与请求的代理服务器(或任何其他服务器)或处理请求的服务器上。”那么在这种情况下客户端缓存会发生什么?
    【解决方案2】:

    响应标头强制执行缓存控制。解决方案不是为需要缓存的控制器操作设置响应标头。我现在不使用OutputCache,而是使用自定义缓存属性,该属性还在请求项字典中设置ISCACHED 键。我的问题中的代码 sn-p 已更改为:

        protected void Application_EndRequest()
        {
            if (HttpContext.Current.Items["ISCACHED"] == null)
            {
                var cache = HttpContext.Current.Response.Cache;
                cache.SetCacheability(HttpCacheability.NoCache);
                cache.SetNoStore();
                cache.SetExpires(DateTime.Now.AddDays(-1));
            }
        }
    

    我必须将它从 BeginRequest 移动到 EndRequest,以允许操作首先设置 ISCACHED 请求项。如果已设置,则控制器已处理此请求的缓存,否则将禁用缓存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 2014-03-31
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 2012-03-03
      相关资源
      最近更新 更多