2010-02-01 31 views
4

我試圖建立一個自定義驗證,我檢查角色是否包含用戶。而且我遇到了字符串數組的問題,檢查它是否包含特定值的最佳方法是什麼?如果User.IsInRole與字符串數組?

public string[] AuthRoles { get; set; } 


    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 

     if (AuthRoles.Length > 0) 
     { 

      if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
      { 

       RedirectToRoute(filterContext, 
       new 
       { 
        controller = "AdminLogin", 
        action = "AdminLogin" 
       }); 

      } 
      else 
      { 
       bool isAuthorized = filterContext.HttpContext.User.IsInRole(this.AuthRoles.??); 

       if (!isAuthorized) 
        throw new UnauthorizedAccessException("You are not authorized to view this page"); 
      } 
     } 
     else 
     { 
      throw new InvalidOperationException("No Role Specified"); 
     } 

我應該如何修改User.IsInRole檢查,因此處理陣列?

回答

12

如何:

bool isAuthorized = 
    this.AuthRoles.Any(r => filterContext.HttpContext.User.IsInRole(r)); 

編輯:(假設是任何角色的成員就足以授權)

8

如果您希望用戶必須在AuthRoles所有角色在同一時間,你應該:

bool isAuthorized = 
     Array.TrueForAll(AuthRoles, filterContext.HttpContext.User.IsInRole); 

如果只是被必需的角色至少一個成員就足夠了,使用Any

bool isAuthorized = AuthRoles.Any(filterContext.HttpContext.User.IsInRole); 
1

您需要檢查每個字符串

bool isAuthorized = false; 

foreach(string role in AuthRoles) 
{ 
    if(filterContext.HttpContext.User.IsInRole(role)) 
    isAuthorized = true; 
} 
+1

我的解決方案只需要用戶是角色之一的成員。所以這取決於你想要的東西。 – AaronLS

2

你可以用一個簡單的LINQ表達式做到這一點:

bool isAuthorized = AuthRoles.All(filterContext.HttpContext.User.IsInRole); 
相關問題