创建您自己的属性并从 AuthorizeAttribute 派生。然后覆盖 AuthorizeCore 方法并通过验证包含空格的角色实现您自己的逻辑。
一个例子可能是这样的:
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()
{
}