2015-04-04 107 views
1

MVC C#中有沒有一種方法允許尚未分配角色的用戶使用。授權在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.... 
} 
+0

只要有另一個控制器......你並不需要的一切推到一個單一的控制器。這是糟糕的設計。 – Phill 2015-04-04 14:31:14

回答

2

您可以創建自定義的授權屬性來實現這一

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 
{ 
} 
+0

這個答案是正確的,但是在Action中你仍然使用Authorize屬性,而不是自定義屬性。你需要解決這個問題。 – ataravati 2015-04-04 20:01:28

+0

@ataravati謝謝修復 – 2015-04-04 20:42:52

+0

不客氣。但是,你不需要'角色=「」',是嗎? – ataravati 2015-04-05 21:18:00