How can i display the Role name for a user in ASP.NET

7.6k views Asked by At

I have a MasterPage in which I display two things: one is the user name which I display with the following command <%: Context.User.Identity.GetUserName() %> and one is the user role.

How can i display it?

Thank you.

2

There are 2 answers

2
Jon Koivula On BEST ANSWER

Try it like this if you have access to UserManager:

UserManager.FindByName(Context.User.Identity.GetUserName()).Roles

Or if you have a access to any Identity based user you should be able to get roles also like this:

AppUser.Roles;

Or search any Identity user with specific name and get its roles:

UserManager.FindByName("Name").Roles;

I'm using Identity 2.0

UPDATE:

So if you have access UserManager and RoleManager in master page code, you could write a method, which gets user roles like this:

    public List<string> GetUserRoles(string username)
    {
        List<string> ListOfRoleNames = new List<string>();
        var ListOfRoleIds = UserManager.FindByName(username).Roles.Select(x => x.RoleId).ToList();
        foreach(string id in ListOfRoleIds)
        {
            string rolename = RoleManager.FindById(id).Name;
            ListOfRoleNames.Add(rolename);
        }

        return ListOfRoleNames;
    }

Then it's up to you how you call this in your view or populate these roles to user while loading page.

0
hutchonoid On

As you are using the Web Forms view engine, I am assuming you must be using asp.net Membership as that was available for MVC 2.0.

There can be multiple roles assigned to a user, the following will loop and print them out:

<% foreach(var role in Roles.GetRolesForUser())
{ %>
     <%:role%>
<% } %>