您可以創建自定義的授權屬性來實現這一
public class MyAuthorizationAttribute : AuthorizeAttribute
{
private bool allowUserWithNoRole = false;
public MyAuthorizationAttribute (bool AllowUserWithNoRole) : base()
{
this.allowUserWithNoRole = allowUserWithNoRole;
}
}
在你AuthorizeCore執行您需要檢查這是角色== 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
{
}
只要有另一個控制器......你並不需要的一切推到一個單一的控制器。這是糟糕的設計。 – Phill 2015-04-04 14:31:14