【问题标题】:Prevent Caching of Attributes in ASP.NET MVC, force Attribute Execution every time an Action is Executed防止在 ASP.NET MVC 中缓存属性,每次执行操作时强制执行属性
【发布时间】:2009-09-17 21:37:33
【问题描述】:

根据各种文章(例如herehere),当控制器操作时,ASP.NET MVC 操作的属性结果可能会缓存并且不会再次执行被调用。

在我的情况下不需要这种行为(例如,我有一个基于我自己的属性和 IP 的授权系统、每次都需要执行的角色检查以及其他事情)。

如何防止 ASP.NET MVC 缓存我的属性/属性执行结果并保证它们每次都执行

【问题讨论】:

  • 澄清一下,缓存是由 ASP.NET 完成的,而不是 ASP.NET MVC。这就是在属性内部很难做到这一点的部分原因!

标签: asp.net-mvc attributes action-filter


【解决方案1】:

查看 AuthorizeAttribute 的源代码(在 Codeplex 上或通过 Reflector),了解它如何关闭授权页面的缓存。我在派生自 AuthorizeAttribute 的自定义授权属性上将其重构为一个单独的方法。

protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
{
    validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
}

protected void SetCachePolicy( AuthorizationContext filterContext )
{
    // ** IMPORTANT **
    // Since we're performing authorization at the action level, the authorization code runs
    // after the output caching module. In the worst case this could allow an authorized user
    // to cause the page to be cached, then an unauthorized user would later be served the
    // cached page. We work around this by telling proxies not to cache the sensitive page,
    // then we hook our custom authorization code into the caching mechanism so that we have
    // the final say on whether a page should be served from the cache.
    HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
    cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
    cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
}

【讨论】:

    【解决方案2】:

    我刚写完a spirited discussion with Craig Stuntz(你列出的第一篇文章的作者)。

    我最终将 AuthorizeAttribute 与 AuthorizeCore 一起使用,以保证即使在页面被缓存的情况下也会调用授权。

    【讨论】:

    • 我的中间解决方案是在 OnActionExecuted 期间简单地禁用响应中的所有缓存。当 AuthorizeCore 应该为我做同样的事情时,它看起来确实有点笨拙。
    • 这里需要澄清一下:stackoverflow.com/questions/1441799/…
    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多