For the life of me I cannot figure out how to simply add roles to my MVC 5 application. This was such a breeze in MVC 4.
The tables are there out of the box,
AspNetRoles, which has an Id and Name ("Admin", "User", etc...)
AspNetUsers, which has an Id and other user fields
AspNetUserRoles - this table has a UserId and RoleId, which is mapped to the tables above.
I want to be able to check to see if a signed in user has the "admin" role or just a "user" role.
Here is what I have tried:
if (User.IsInRole("Admin"))
{
//do something
}
The value always come back false.
I also tried:
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var userRole = UserManager.GetRoles(user.GetUserId());
if (userRole[0] == "Admin")
{
// do something
}
This throws error :
"Index was out of range. Must be non-negative and less than the size of the collection."
Is there a simple method that can get the role for the current logged in user? I have seen references to using Role Manager, but I have been unable to get that to work. I believe that was for Identity 1.0
Thanks