我正在使用 MVC3/4。但这只是授权中的一般问题。
我有一个角色在数据库中名为“Trip Leader”,其中包含一个空格。
我尝试了 [Authorize(Roles="'Trip Leader', Administrator")]
但没有成功。谁能帮忙?
最佳答案
创建您自己的属性并派生自 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()
{
}
关于c# - 如果角色包含空格,如何编写 AuthorizeAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954907/