Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc 5 check user role

Tags:

How in mvc 5 I can found out role of logged user?

I made the user by this code

    private bool AddUserAndRole()     {         IdentityResult ir;         var rm = new RoleManager<IdentityRole>             (new RoleStore<IdentityRole>(new ApplicationDbContext()));         ir = rm.Create(new IdentityRole("admin"));          var user = new ApplicationUser() { UserName = "Admin" };         var result = UserManager.Create(user, "somepassword");         UserManager.AddToRole(user.Id, "admin");          return true;      } 

After I loggin on site by that user. How in controller I can check if that user have role == "admin" or not? I found only one way which doesnt look works fast.

        var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));         var role = rm.FindByName("admin");         bool result = User.IsInRole(role.Name); //true 

Do we have other ways?

like image 528
Duke Avatar asked Oct 30 '13 17:10

Duke


People also ask

How do I get user role in .NET core identity?

Show activity on this post. var user = await _userManager. FindByIdAsync(UserId); var roles = await _userManager. GetRolesAsync(user); return OK(new { User = user, Roles = roles });


1 Answers

bool result = User.IsInRole("admin")  

Much easier. :)

like image 53
Alex Dresko Avatar answered Sep 21 '22 12:09

Alex Dresko