C# 授权所有未在MVC中分配角色的用户

C# 授权所有未在MVC中分配角色的用户,c#,asp.net-mvc,C#,Asp.net Mvc,MVC中是否有一种方法允许尚未分配角色的用户 比如说 [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 actio

MVC中是否有一种方法允许尚未分配角色的用户

比如说

[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....
}

您可以创建自定义授权属性来实现此目的

public class MyAuthorizationAttribute : AuthorizeAttribute
{
    private bool allowUserWithNoRole = false;
    public MyAuthorizationAttribute (bool AllowUserWithNoRole) : base()
    {
        this.allowUserWithNoRole = allowUserWithNoRole;
    }
}
在AuthorizeCore中,执行所需的检查,即roles==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的字段。当角色为空时,这将处理您希望授权具有不同行为的实例

最后,将此自定义属性设置在操作之上

[MyAuthorization(AllowUserWithNoRole=true, Roles="")
public ActionResult ChooseYourRole() 
//I want only authenticated users with no roles assigned to access this action
{
}

只要有另一个控制器。。。你不需要把所有的东西都塞进一个控制器。这是一个糟糕的设计。这个答案是正确的,但在操作中您仍然使用Authorize属性,而不是custom属性。你需要解决这个问题,不客气。但是,您不需要角色=,是吗?