如何从Controller获取角色名称到Custom AuthorizeAttribute class?

How to get the name of the role from the Controller to the Custom AuthorizeAttribute class?

我正在开发 MVC 应用程序并使用 ASP.NET 身份作为用户角色。我已将 AuthorizeAttribute class 的 3 个功能覆盖为:

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private ApplicationDbContext context = new ApplicationDbContext();
        private readonly string[] allowedroles;        
        public CustomAuthorizeAttribute(params string[] roles)
        { this.allowedroles = roles; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string usr = httpContext.User.Identity.Name;
            var userId = context.Users.Where(item => item.UserName == usr).Single().Id;
            var uroles = context.Roles.ToList();
            bool authorize = false;
            foreach (var role in uroles)
            {
                var user = context.Users.Where(u => u.Roles.Any(r => r.RoleId == role.Id)).ToList();
                if (user.Count() > 0)
                { authorize = true; }
            }
            return authorize;
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        { filterContext.Result = new HttpUnauthorizedResult("Access is Denied!"); }
    }

现在我的控制器授权为:

[CustomAuthorize(Roles="Delete COA")]

即使在 dbo.AspNetRoles 表中我没有为名称为 "Delete COA" 的当前用户分配任何角色,我的代码仍会授权当前用户使用它。但是由于我的 CustomeAuthorizeAttribute Class 没有从控制器获取角色属性的名称,我无法根据当前用户的角色进行过滤。

改为构造函数代码

this.allowedroles = roles;

获取字符串为:

roles = {string[0]}

但我需要这里的角色名称。这里有什么问题?

您似乎在使用 属性 作为参数。因为 AuthorizeAttribute 已经有 Role 属性 你可以简单地使用它。

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    private ApplicationDbContext context = new ApplicationDbContext(); 

    // you don't need the constrictor and private roles field  

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // spiting different roles by ',' 
        var roles=this.Rols.Split(',');
        // rest of your code
    }
}

然后您可以申请任何行动:

[CustomAuthorize(Roles="Delete COA")]
public ActionResoult MyFancyAction(){}

或者对于多个角色,您可以:

[CustomAuthorize(Roles="FirstRole,SecondRole,AndSoOn")]
public ActionResoult MyFancyAction(){}