Checking if a user is in a role in asp.net mvc Identity

I found out the solution, in case anyone else is having this problem.

The "IsInRole" is expecting a User.Id - not a UserName string - so I changed to:

            if (!userManager.IsInRole(user.Id, "Admin"))
            {
                userManager.AddToRole(user.Id, "Admin");
            }

So the working code becomes:

    ApplicationDbContext userscontext = new ApplicationDbContext();
    var userStore = new UserStore<ApplicationUser>(userscontext);
    var userManager = new UserManager<ApplicationUser>(userStore);

    var roleStore = new RoleStore<IdentityRole>(userscontext);
    var roleManager = new RoleManager<IdentityRole>(roleStore);

    // Create Role
    if (!roleManager.RoleExists("Admin"))
    { 
        roleManager.Create(new IdentityRole("Admin"));
    }

    if(!userscontext.Users.Any(x=> x.UserName=="marktest"))
    {
        // Create User
        var user = new ApplicationUser { UserName = "marktest", Email = "[email protected]" };
        userManager.Create(user, "Pa$$W0rD!");

        // Add User To Role
        if (!userManager.IsInRole(user.Id, "Admin"))
            {
                userManager.AddToRole(user.Id, "Admin");
            }


    }

I hope that helps,

Mark


Simplest thing in life;

bool isAdmin= User.IsInRole("admin")