如果角色包含空格,如何编写AuthorizeAttribute

我正在使用MVC3 / 4。 但这只是授权中的一般性问题。

我所拥有的一个角色是在数据库中命名为“Trip Leader”,其中包含一个空格。

我试过[Authorize(Roles="'Trip Leader', Administrator")]但它没能奏效。 有人可以帮忙吗?

创建自己的属性并从AuthorizeAttribute派生。 然后重写AuthorizeCore方法并实现您自己的逻辑,并对包含空格的角色进行validation。

一个例子可能是这样的:

 public class CustomAuthAttribute : AuthorizeAttribute { private readonly IUserRoleService _userRoleService; private string[] _allowedRoles; public CustomAuthAttribute(params string[] roles) { _userRoleService = new UserRoleService(); _allowedRoles = roles; } protected override bool AuthorizeCore(HttpContextBase httpContext) { //something like this. var userName = httpContext.User.Identity.Name; var userRoles = _userRoleService .GetUserRoles(userName); // return list of strings return _allowedRoles.Any(x => userRoles.Contains(x)); } 

}

用法

 [CustomAuth("role withspace","admin")] public ActionResult Index() { } 

试试这个:

 [Authorize(Roles="Trip Leader")] [Authorize(Roles="Administrator")] 

编辑:上述代码要求用户履行这两个角色。 如果您正在寻找/或授权,请尝试以下方法:

 [Authorize(Roles="Trip Leader, Administrator")] 

我无法得到其他工作的答案。 我的角色中包含逗号,不适用于原始的AuthorizeAttribute。

  //Custom Authorize class that derives from the existing AuthorizeAttribute public class CustomAuthorizeAttribute : AuthorizeAttribute { private string[] _allowedRoles; public CustomAuthorizeAttribute(params string[] roles) { //allowed roles _allowedRoles = roles; } protected override bool AuthorizeCore(HttpContextBase httpContext) { var roleManager = httpContext.GetOwinContext().Get(); //Grab all of the Roles for the current user var roles = roleManager.GetRoles(httpContext.User.Identity.GetUserId()); //Determine if they are currently in any of the required roles (and allow / disallow accordingly) return _allowedRoles.Any(x => roles.Contains(x)); } }