在MVC C#中是否有办法允许尚未分配角色的用户。
例如
[Authorize(Roles="a, b, c, d")]
public class SomeController : Controller
{
[Authorize(Roles="")
public ActionResult ChooseYourRole()
//I want only authenticated users with no roles assigned to access this action
{
}
....other actions....
}
答案 0 :(得分:2)
您可以创建自定义授权属性来实现此目的
public class MyAuthorizationAttribute : AuthorizeAttribute
{
private bool allowUserWithNoRole = false;
public MyAuthorizationAttribute (bool AllowUserWithNoRole) : base()
{
this.allowUserWithNoRole = allowUserWithNoRole;
}
}
在AuthorizeCore中执行所需的检查,即role == 0
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsAuthenticated)
return false;
if (allowUserWithNoRole && Roles.Count() == 0)
{
return true;
}
else {
//Perform additional checks for authorization
}
}
我还添加了一个名为allowUserWithNoRole的字段。当角色空置时,这将处理您希望授权的行为不同的实例。
最后,将此自定义属性设置在Action
上方[MyAuthorization(AllowUserWithNoRole=true, Roles="")
public ActionResult ChooseYourRole()
//I want only authenticated users with no roles assigned to access this action
{
}