Bla*_*ise 6 c# authorization asp.net-mvc-3
我正在使用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));
}
}
Run Code Online (Sandbox Code Playgroud)
用法
[CustomAuth("role withspace","admin")]
public ActionResult Index()
{
}
Run Code Online (Sandbox Code Playgroud)