Get Role name in IdentityUserRole 2.0 in ASP.NET
Asked Answered
C

4

12

Before the update of the dll's in the Entity Framework i was able to do this

user.Roles.Where(r => r.Role.Name == "Admin").FisrtOrDefault(); 

Now, i can only do r.RoleId, and i can't find a way to retreive the name of thar Role Id. I'm using this in my controllers and in my AuthorizeAttribute class.

Can someone help me here?

Regards

Casting answered 5/6, 2015 at 15:54 Comment(0)
L
8

Ask the RoleMananger?

RoleManager.Roles.
// or
RoleManager.FindByIdAsync()
// or 
RoleManager.FindByNameAsync()

You may want to take some time and learn the new security features in Asp.Net Security and Asp.Net Identity.

Lesko answered 5/6, 2015 at 16:32 Comment(0)
S
9

Try this

string id = UserManager.FindByEmail(model.Email).Id;
IList<string> roleNames=UserManager.GetRoles(id);
Suzisuzie answered 30/6, 2016 at 12:20 Comment(2)
how to list it now, i mean in viewEmergency
This helped a lot. Thank you Neeraj.Handful
L
8

Ask the RoleMananger?

RoleManager.Roles.
// or
RoleManager.FindByIdAsync()
// or 
RoleManager.FindByNameAsync()

You may want to take some time and learn the new security features in Asp.Net Security and Asp.Net Identity.

Lesko answered 5/6, 2015 at 16:32 Comment(0)
R
2

I've just had almost exactly the same issue and I solved it like this:

public class UserRole : IdentityUserRole
{
    public virtual Role Role { get; set; } // add this to see roles
    public virtual User User { get; set; } // add this to see users
}

Now your original code user.Roles.Where(r => r.Role.Name == "Admin").FirstOrDefault(); will work, which could be handy if you don't have easy access to the RoleManager for any reason.

Redfin answered 14/2, 2018 at 9:52 Comment(0)
I
1

If your aim is to check if a user is in a role you can access it from the IPrincipal.User object in an action

User.IsInRole("Admin");
Infield answered 5/6, 2015 at 16:39 Comment(1)
this is in the View, and my question was in the backend...ty anywayCasting

© 2022 - 2024 — McMap. All rights reserved.