我想缓存 MVC 操作的输出。但是:
1) 如果我全局应用 OutputCacheAttribute
,则存在风险,因为它会为所有用户缓存所有内容。
2)如果我全局应用OutputCacheAttribute
,然后在需要授权的操作上应用Authorize
属性,仍然无法解决问题。无论用户是否获得授权,所有输出仍然会被缓存。
3)如果我仅在选择操作上应用OutputCacheAttribute
(不是全局的,而是),并且在所有需要授权的操作上应用AuthorizeAttribute
,那么就没有安全性威胁,但存在性能成本。每个需要身份验证的页面都需要发出新的 Http 请求。
我想找到一个中间立场,以便选定的页面和/或选定的请求类型 (HTTP GET) 缓存在客户端,但前提是用户经过身份验证。如果用户注销并访问缓存页面/操作的 url,他一定无法看到内容。
有办法实现吗?
最佳答案
VaryByCustom is what you want
。将其放入您的 Global.asax 文件中:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
// use this algorithm to determine cacheability for "IsAuthenticated"
if ("IsAuthenticated".Equals(custom, StringComparison.OrdinalIgnoreCase))
{
// cache content when user is authenticated
if (User.Identity.IsAuthenticated) return "true";
// do not cache when user is not authenticated
return null;
}
return base.GetVaryByCustomString(context, custom);
}
...然后在要缓存的操作方法上使用类似的内容:
[OutputCache(VaryByCustom = "IsAuthenticated", Duration = 1800,
Location = OutputCacheLocation.Client)]
public virtual ActionResult Index()
{ ... }
关于asp.net - 缓存 MVC 操作的输出,但仅对经过身份验证的用户使用缓存版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15499686/