【问题标题】:Caching output of MVC actions but using the cached version only for authenticated users缓存 MVC 操作的输出,但仅对经过身份验证的用户使用缓存版本
【发布时间】:2013-03-19 12:35:23
【问题描述】:

我想缓存我的 MVC 操作的输出。然而:

1) 如果我在全局范围内应用OutputCacheAttribute,这是有风险的,因为它会为所有用户缓存所有内容。

2) 如果我在全局范围内应用OutputCacheAttribute,然后将Authorize 属性应用于那些需要授权的操作,那仍然不能解决问题。无论用户是否被授权,所有输出仍然被缓存。

3) 如果我只在选择的操作上应用OutputCacheAttribute(不是全局但),并且在所有需要授权的操作上使用AuthorizeAttribute,那么就没有安全威胁,但有性能成本。每个需要身份验证的页面都需要发出新的 Http 请求。

我想找到一个中间地带,以便在客户端缓存所选页面和/或所选类型的请求 (HTTP GET),但前提是用户已通过身份验证。如果用户注销并访问缓存页面/动作的 url,他一定无法看到内容。

有没有办法实现这个?

【问题讨论】:

    标签: asp.net asp.net-mvc caching outputcache output-caching


    【解决方案1】:

    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()
    { ... }
    

    【讨论】:

    • -1 真的吗?我刚刚对此进行了测试,并且可以正常工作。未经身份验证的用户在每个请求上都会获得一个新的服务器副本,而经过身份验证的用户会获得一个缓存副本。这与我之前没有实际代码的答案完全相同。
    猜你喜欢
    • 2012-07-24
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2019-08-26
    • 2017-03-02
    相关资源
    最近更新 更多