asp.net mvc – asp.net mvc decorate [Authorize()]与多个枚举

我有一个控制器,我想要两个角色能够访问它。 1-admin或2 – 主持人

我知道你可以做[授权(角色=“管理员,版主”)],但我有我的角色在枚举。用枚举我只能授权一个角色。我不知道如何授权两个。

我试过像[Authorize(Roles = MyEnum.Admin,MyEnum.Moderator)]但是不会编译。

有人曾经建议:

[Authorize(Roles=MyEnum.Admin)]
 [Authorize(MyEnum.Moderator)]
 public ActionResult myAction()
 {
 }

但它不工作作为OR。我认为在这种情况下,用户必须是BOTH角色的一部分。我可以忽略一些语法吗?或者是这种情况下,我必须滚动我自己的自定义授权?

解决方法

尝试使用位OR运算符:
[Authorize(Roles= MyEnum.Admin | MyEnum.Moderator)]
public ActionResult myAction()
{
}

如果这不工作,你可以自己滚。我目前只是在我的项目。这是我做的:

public class AuthWhereRole : AuthorizeAttribute
{
    /// <summary>
    /// Add the allowed roles to this property.
    /// </summary>
    public UserRole Is;

    /// <summary>
    /// Checks to see if the user is authenticated and has the
    /// correct role to access a particular view.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        // Make sure the user is authenticated.
        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        UserRole role = someUser.Role; // Load the user's role here

        // Perform a bitwise operation to see if the user's role
        // is in the passed in role values.
        if (Is != 0 && ((Is & role) != role))
            return false;

        return true;
    }
}

// Example Use
[AuthWhereRole(Is=MyEnum.Admin|MyEnum.Newbie)]
public ActionResult test() {}

此外,请确保为您的枚举添加一个flags属性,并确保它们都从1开始计算。喜欢这个:

[Flags]
public enum Roles
{
    Admin = 1,Moderator = 1 << 1,Newbie = 1 << 2
    etc...
}

左位移位给出值1,2,4,8,16等等。

嗯,我希望这有一点帮助。

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....