【问题标题】:SetLastModified ignored when using an OutputCacheAttribute使用 OutputCacheAttribute 时忽略 SetLastModified
【发布时间】:2011-02-09 13:57:30
【问题描述】:

我有一个 ASP.NET MVC 方法(.NET 4.0 上的 v3.0)设置如下:

[OutputCache(Duration = 31536000, Location = OutputCacheLocation.Any)]
public virtual ActionResult Item()
{
    this.Response.Cache.SetLastModified(new DateTime(2011, 01, 01));
    return this.Content("hello world", "text/plain");
}

我希望这会在返回时将 Last-Modified 标头设置为指定的 Mon, 07 Feb 2011 00:00:00 GMT,但它实际上是作为输出第一次缓存在输出缓存中的日期(即第一次方法在 IIS 被重置后被调用)。

如果我注释掉 [OutputCache] 属性以便没有完成输出缓存,那么 Last-Modified 标头会按预期返回,因此似乎输出缓存基础结构中的某些东西选择忽略我为此指定的值.

知道它为什么会这样做吗?有没有办法让它使用我指定的值作为Last-Modified 日期?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 http-caching output-caching


    【解决方案1】:

    好吧,我从来没有弄清楚发生这种情况的原因,但它看起来像是 [OutputCache] 属性使用的 ASP.NET 页面缓存基础结构中的某个错误。

    我最终编写了一个自定义的[HttpCache] 属性,它具有几乎相同的公共接口,但它直接调用Response.Cache 对象上的适当缓存方法,而不是委托给 ASP.NET 页面缓存基础结构。

    效果很好。可惜内置属性没有。

    【讨论】:

    • 嗨,格雷格!在过去的两周里,我一直在努力解决同样的问题。无法弄清楚为什么在使用 outputCacheAttribute 时忽略 Last-Modified。这是一个很老的帖子,但如果你看到它,你可以解释一下你是如何实现你的自定义 HttpCache 的?谢谢!
    【解决方案2】:

    在 Controller 的 OnResultExecuting 事件期间,[OutputCache] 创建一个 System.Web.UI.Page 的实例来处理属性中指定的缓存属性。他们这样做是因为 Page 已经有了将 OutputCacheParameters 转换为实际 http 缓存指令的逻辑。

    https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/OutputCacheAttribute.cs

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
    
            if (!filterContext.IsChildAction)
            {
                // we need to call ProcessRequest() since there's no other way to set the Page.Response intrinsic
                using (OutputCachedPage page = new OutputCachedPage(_cacheSettings))
                {
                    page.ProcessRequest(HttpContext.Current);
                }
            }
        }
    

    OutputCacheAttribute 基本上将输出从原始处理程序(控制器)复制到为配置缓存而创建的页面。

    这里的缺点是添加到原始 HttpResponse 的标头不会被复制到新的处理程序(页面)。这意味着不可能在控制器中的 Response 上设置标头。实际处理请求的 Page 会忽略这些标头。

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 2015-03-07
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多