2015-10-05 56 views
0

我嘗試了下面的代碼來獲取用戶的所有角色對象(即ApplicationRole而不是IdentityUserRole)。如何查找用戶在asp.net身份2.0中的所有ApplicationRoles

string userId = User.Identity.GetUserId(); 

var RoleManager = this.HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); 
var UserManager = this.HttpContext.GetOwinContext().Get<ApplicationUserManager>(); 

// var u = RoleManager.FindByName("").Users; 
// var r = UserManager.FindById(userId).Roles; 

var roleNames = ((ClaimsIdentity)User.Identity).Claims 
    .Where(c => c.Type == ClaimTypes.Role) 
    .Select(c => c.Value); 

var userRoles = (from roles in RoleManager.Roles 
        where roleNames.Contains(roles.Name) 
        select roles 
        ).ToList(); 

但它看起來不一致和微不足道,它只適用於當前用戶。我希望能有更好的方式來做到這一點。

編輯1:

我RoleManager是從IdentityRole派生的類有一些額外的屬性例如描述。

public class ApplicationRole : IdentityRole 
{ 
    public ApplicationRole() : base() { } 
    public ApplicationRole(string name, string description) 
     : base(name) 
    { 
     this.Description = description; 
    } 
    public virtual string Description { get; set; } 
} 

注意:IdentityUserRole/user.Roles/role.Users不是角色。所有這三個代表用戶&角色

+1

你的應用程序的作用是什麼意思? – DavidG

+0

你可以使用user.Roles嗎? –

+1

默認情況下,沒有'ApplicationRole'這樣的東西。 'ApplicationUser',與'IdentityUserRole'有關。如果您確實需要實現自己的用戶角色類(它繼承自IdentityUserRole),那麼您可以覆蓋它,但在此沒有跡象表明您實際上已經這樣做了。 –

回答

0
var selectedRoleNames = from uf in user.UserRoles 
         join r in RoleManager.Roles on uf.RoleID equals r.ID 
         select r; 

這得到給定用戶的角色。如果給定用戶不是當前用戶,則不要使用User.Identity,而是通過UserManager獲取用戶。

或者,如果你已經有任何的用戶ID,然後...

var selectedRoleNames = from r in RoleManager.Roles 
         where r.Users.Select(u => u.UserId).Contains(user.Id) 
         select r; 
相關問題