22

I'm having an issue seeding my database with users and roles.

The User and the Role are both created (I can see them in the database after the error is thrown).

However, when I try to check if the user is in a role, I get an exception.

My code is:

    public class tbInitializer<T> : DropCreateDatabaseAlways<tbContext>
    {
    protected override void Seed(tbContext context)
    {
        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);


        if(!userscontext.Users.Any(x=> x.UserName=="marktest"))
        {
            var user = new ApplicationUser { UserName = "marktest", Email = "marktest@gmail.com" };
            userManager.Create(user, "Pa$$W0rD!");
        }

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

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

However, on the line:

if(!userManager.IsInRole("marktest","Admin"))

An exception is thrown with the error: UserId not found.

The User and the Role are both in the database when I check after the exception is thrown:

Shows User Added to DB

Shows Role Added to DB

Can anyone see what I'm doing wrong?

Thanks for any help,

Mark

Mark
  • 7,778
  • 24
  • 89
  • 147

3 Answers3

38

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 = "marktest@gmail.com" };
        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

Mark
  • 7,778
  • 24
  • 89
  • 147
  • My code looks the same yet I still get the UserId not found in the same place – bob.mazzo Mar 09 '16 at 23:39
  • Just a heads-up in case anyone else trips up - haven't check the sync method, but the `userManager.IsInRole` method takes a **user**, not a string for the id. – Avrohom Yisroel Jun 08 '22 at 15:43
19

Simplest thing in life;

bool isAdmin= User.IsInRole("admin") 
Baqer Naqvi
  • 6,011
  • 3
  • 50
  • 68
  • For some reason, this does not work for me! I'm using .Net Core with JWT Authentication. – J86 Aug 15 '17 at 12:03
  • try using @if (Roles.IsUserInRole(Model.UserName, "Administrator")) if it works – Baqer Naqvi Aug 16 '17 at 13:01
  • J86, for this to work with JWT Authentication, you have to add the roles in the Tokens ClaimsIdentity first, as explained in this post: https://stackoverflow.com/questions/42036810/asp-net-core-jwt-mapping-role-claims-to-claimsidentity – Scott Duncan Dec 20 '19 at 16:21
0

To add to Mark's post above in its still pretty much the same in .NET Core 3.1 Identity only difference with the async method IsInRoleAsync you have to pass in the IdentityUser type object:

var userInRole = await _userManager.IsInRoleAsync(user, role);

Then you can apply your logic afterwards (in my case I was doing two things, first checking the role actually exists and then checking if the user isn't already assigned to that role).

Trevor
  • 1,561
  • 1
  • 20
  • 28