2012-03-01 27 views
6

Tôi đang tạo thuộc tính ủy quyền tùy chỉnh của riêng mình, ghi đè phương thức AuthorizeCore và muốn biết liệu có thể truy cập các Vai trò đã được chuyển vào thẻ thuộc tính ủy quyền hay không.Truy cập các vai trò từ thuộc tính ủy quyền tùy chỉnh

Vì vậy, ví dụ nếu tôi có điều này:

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

Có thể truy cập vào các từ bên trong ở đây:

protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
    } 

Sau đó tôi có thể chia chuỗi và tạo một mảng.

+0

nhìn vào đây http://stackoverflow.com/a/9479442/745331 – Yorgo

Trả lời

9

Bạn có thể điều này this.Roles là một chuỗi mà bạn cần chia nhỏ.

Mã nguồn có sẵn miễn phí.

Việc thực hiện AuthorizeCore mặc định:

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; 
} 

Và họ có một chức năng phân chia nội bộ mà trông như thế này:

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(); 
}