3

Using ASP.NET MVC5 user identity, I am trying to display IdentityUser's role names in view.

It seems like Identity user has Roles property, which represent collection of IdentityUserRole, instead of IdentityRole. The difference is IdentityUserRole represents association between IdentityUser and IdentityRole, while IdentityRole is the actual Role model [+]. Apparently there is no navigation defined between IdentityUser and IdentityRole. So all we get is RoleId from IdentityUserRole.

  1. Is there an easy way to get the roles names?
  2. Using Fluent API, can we define a virtual navigation property between IdentityRole and IdentityUserRole to get name easily throughout the project?
  3. If it is by design, what is the benefit of not letting us obtain IdentityRole straightforwardly?
Annie
  • 3,090
  • 9
  • 36
  • 74
  • I would suggest you to get roles in controller / action and pass it to the view as a property, that means part of the model you are passing to view. If not you may need to extend IPrincipal or IIdentity properties to include Roles, then you can get it something like HttpContext.Current.User.Identity.Roles. – DSR Nov 24 '14 at 10:37
  • 1
    I'm assuming that you found an answer to this by now even though there is nothing here so I'd like to know what it is. At this point I am storing a dictionary representation of the IdentityRole objects in the ViewBag and accessing them by IdentityUserRole.RoleId in the view code. It works but I am not thrilled with it. – Christopher King Apr 08 '15 at 02:01

1 Answers1

-1

You can select a userrole in identity using the rolemanager

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this.dbcontext));

from the user get the userrole and then select the name from that role

roleManager.FindById(user.RoleId).Name
MFasseur
  • 335
  • 3
  • 7