Tom
Tom

Reputation: 4087

Asp MVC: How get roles from ApplicationUser

In ASP.NET MVC 5, in a controller, I have take the user that has make the request with:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

With the ApplicationUser instance, how can i get all the Roles of the user?

Upvotes: 5

Views: 16322

Answers (2)

Iman
Iman

Reputation: 18876

        List<string> roles = new UserManager().GetRoles(userIdString)).ToList();

below needed classes were created automatically in ASP.NET 4.5 project using VS 2015 using . the file name is IdentityModels.cs.

default 4 Nuget packages are installed including Microsoft.AspNet.WebApi v5.2.3

 public class UserManager : UserManager<ApplicationUser>
    {
        public UserManager()
            : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
        {
        }
    }

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }


public class ApplicationUser : IdentityUser
{
}

Upvotes: 0

IMujagic
IMujagic

Reputation: 1259

You can get user and assigned roles by using UserManager.

var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

and then you can get your user like you already did, and also you can get roles for particular user by calling GetRoles method

userManager.GetRoles(userId);

Upvotes: 12

Related Questions