加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 19:05:31 所属栏目:asp.Net 来源:网络整理
导读:我有一个控制器,我想要两个角色能够访问它。 1-admin或2 – 主持人 我知道你可以做[授权(角色=“管理员,版主”)],但我有我的角色在枚举。用枚举我只能授权一个角色。我不知道如何授权两个。 我试过像[Authorize(Roles = MyEnum.Admin,MyEnum.Moderator)]
我有一个控制器,我想要两个角色能够访问它。 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等等。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读