c# - 在 Controller 中的操作之间交换属性

标签 c# asp.net asp.net-mvc attributes httpcontext

我问了a similar question答案是我根本不需要这样做。虽然这对于该方法是正确的,但这对我没有帮助。

我有以下操作:

[MyCaching]
[MyUserAuth]
public class MyMagicController:Controller {
   public ActionResult GetLoans() {
      return GetLoansForThisUser();
   }
}

MyUserAuth 是一个属性,用于检查用户是否具有获取数据的权限。此信息是从数据库中检索的,不能(纯粹)通过 HttpContext 检索。一些用户是管理员,他们应该看到更多。

如果用户具有正常访问权限(如 90% 的用户),[MyCaching] 中的缓存机制 - 属性应该启动并且内容应该从缓存返回。

如果是Administrator,Cache应该不会返回,也不会被填充,因为内容不一样。

所以我需要找到一种方法让 [MyUserAuth] 告诉 [MyCaching] 该信息。有没有直接的方法来实现这一目标? 如果不是,我可以为此“滥用” HttpContext 吗?例如:

public class MyAuthAttribute:AuthenticationAttribute
    // ...
    public void CheckPermissions(HttpContext context) {
        context.Items.Add("isAdmin",true);
    }
}

public class MyCachingAttribute:ActionAttribute {
    // ...
    public void GetCache(HttpContext context) {
        if (context.Items["isAdmin"]) {
            return // dontcache;
        }
    }
}

然后将 MyUserAuth 放在 MyCaching 之前?

最佳答案

您可以在身份验证中设置角色或声明“isAdmin”,您可以通过 HttpContext 在 MyCaching 中检查它

关于c# - 在 Controller 中的操作之间交换属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36794385/

相关文章:

c# - BackgroundDownloader 不适用于 Windows 10 移动版 UWP?

javascript - 在里面用htmlhelpers动态创建div?

c# - 部署程序时出现 System.ArgumentOutOfRangeException

c# - 正在监听 808 端口以外的 netTcpbinding?

c# - 有没有办法使 C# 绑定(bind)静态工作?

c# - WCF 服务响应中的意外标记名称

php - 如何在来自 Web 服务器的流式内容上设置只读标志

Asp.net、Silverlight 和 HTTPS - 始终验证证书

asp.net-mvc - 如何将名为 "file[]"的发布数据绑定(bind)到 MVC 模型?

c# - 在上一个操作完成之前,第二个操作在此上下文中启动。接口(interface)上的异步方法