asp.net - 缓存 MVC 操作的输出,但仅对经过身份验证的用户使用缓存版本

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

我想缓存 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/

相关文章:

c# - MVC 5 项目和 Web Api 项目的区别

Docker 从缓存中构建已删除的模块

asp.net-mvc - 添加 TwilioController 基类继承后,Microsoft Azure MVC 3 Web 角色未启动

asp.net-mvc - MVC : How to get controller to render partial view initiated from the view

javascript - 使用计时器更新 d3 生成的圆圈的位置

java - Guava - 缓存一张表并在该缓存上使用 get 方法

java - 在 Ehcache 复制设置中使用 timeToIdleSeconds 参数

c# - 如何在Asp Net Web Api中默认返回404

c# - Nhibernate:连接表并从其他表获取单列

asp.net - 您离不开哪些第三方 ASP.NET 控件或库?