Introduction
In order to get a user's roles in ASP.NET Identity, we use the GetRoles method.
GetRoles
The GetRoles method gets all roles for a given user and returns the result of the operation
as an IList<string>
object.
IList<string> = UserManager.GetRoles(userId);
The GetRoles method is called by the UserManager, which is responsible for performing the user-related operations.
UserManager
We use the GetUserManager method to get the ApplicationUserManager from the Owin context.
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager();
}
private set
{
_userManager = value;
}
}
Example
private IList<string> GetUserRoles(string userId)
{
var roles = UserManager.GetRoles(userId);
return roles;
}
In the above example, we've 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.
Namespaces
In order to use the GetUserManager method, the GetRoles method, and the IdentityResult object, you have to include the following namespaces :
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;