Back to: ASP.NET MVC Tutorial For Beginners and Professionals
How to Get a User Roles in ASP.NET Identity
In this article, I am going to discuss How to Get User Roles in ASP.NET Identity with Examples. Kindly take a look at our previous article, where we discussed How to Assign a User to a Role in ASP.NET Identity.
How to Get a User Roles in ASP.NET Identity
In order to get a user role in ASP.NET Identity, we need to use the GetRoles or GetRolesAsync method. The GetRoles or GetRolesAsync method returns all roles for a given user and returns the result of the operation as an IList<string> object as follows.
IList<string> userRoles = UserManager.GetRoles(userId);
IList<string> userRoles = await UserManager.GetRolesAsync(userId);
The GetRoles method is called by the UserManager, which is responsible for performing the user-related operations in ASP.NET Identity.
UserManager In ASP.NET Identity:
In ASP.NET Identity, we need to use the GetUserManager method to get the ApplicationUserManager from the Owin context as follows.
ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
Example to Get a User Roles in ASP.NET Identity:
So, you can use the following method in ASP.NET MVC Application to get a User Roles using ASP.NET Identity. In the below code, we have declared a method that takes the id of the user we want to get its roles. We pass this id to the GetRoles method that returns all of its roles as a collection of role names. We then return this result set.
private IList<string> GetUserRoles(string userId) { ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); var roles = UserManager.GetRoles(userId); return roles; }
Namespaces:
In order to use the GetUserManager method and the GetRoles method, we have to include the following two namespaces:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
In the next article, I am going to discuss Role-Based Authorization in ASP.NET Identity with Examples. In this article, I try to explain How to Get a User Role in ASP.NET Identity with Examples. I hope you enjoy the article How to Get a User Roles in ASP.NET Identity.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.