2012-03-01 125 views
6

我創建了自己的自定義授權屬性,覆蓋了AuthorizeCore方法,並想知道是否可以訪問已傳遞到授權屬性標籤的角色。從自定義授權屬性訪問角色

因此,舉例來說,如果我有這樣的:

[CustomAuthorize(Roles = "Administrator, Sales, Entry")] 

是否有可能從這裏內部訪問這些:

protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
    } 

然後我可以分割字符串,並創建一個數組。

+0

看看這裏http://stackoverflow.com/a/9479442/745331 – Yorgo 2012-03-01 14:15:56

回答

9

你可以這個this.Roles這是一個你需要拆分的字符串。

源代碼是免費的。

默認AuthorizeCore實現:

protected virtual bool AuthorizeCore(HttpContextBase httpContext) { 
    if (httpContext == null) { 
     throw new ArgumentNullException("httpContext"); 
    } 

    IPrincipal user = httpContext.User; 
    if (!user.Identity.IsAuthenticated) { 
     return false; 
    } 

    if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) { 
     return false; 
    } 

    if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) { 
     return false; 
    } 

    return true; 
} 

而且他們有一個內部分裂的功能,看起來像這樣:

internal static string[] SplitString(string original) { 
    if (String.IsNullOrEmpty(original)) { 
     return new string[0]; 
    } 

    var split = from piece in original.Split(',') 
       let trimmed = piece.Trim() 
       where !String.IsNullOrEmpty(trimmed) 
       select trimmed; 
    return split.ToArray(); 
}