防止在 ASP.NET MVC 中缓存属性,每次执行操作时强制执行属性 [英] Prevent Caching of Attributes in ASP.NET MVC, force Attribute Execution every time an Action is Executed

查看:16
本文介绍了防止在 ASP.NET MVC 中缓存属性,每次执行操作时强制执行属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to various articles (e.g. here and here) attribute results on ASP.NET MVC Actions may be cached and not executed again when a controller action is called.

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

That behavior is not desired in my case (e.g. I have an authorization system based on my own attributes and IPs, role checks that need to execute every time, and other things).

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

How can I prevent ASP.NET MVC from caching my attributes/attribute execution results and guarantee that they are executed every time?

推荐答案

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

Look at the source code for the AuthorizeAttribute (on Codeplex or via Reflector) to see how it goes about turning off caching for authorized pages. I refactored it into a separate method on my custom authorization attribute which derives from 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 */);
}

这篇关于防止在 ASP.NET MVC 中缓存属性,每次执行操作时强制执行属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆