Search code examples
c#asp.netasp.net-identityrolesusermanager

Asp.NET Identity Roles not working when attempting to add Role to User


I am currently adding Roles to our Database using the RoleManager with the CreateAsync(newRoleName) Method - which works correctly. But when I try to query that Role, it always returns that it doesn't exist (even though I can see it in the database).

Can anyone provide some insight on why I am not able to use the Role?

        var roleExists = roleManager.RoleExistsAsync(role);
        if (!roleExists.Result)
        {
            var newRole = new IdentityRole(role)
            {
                Name = role,
                NormalizedName = role.ToUpper(),
            };

            var roleCreated = roleManager.CreateAsync(newRole);

            Thread.Sleep(500);  // Used to get result back first.

            var roleExistsYet = roleManager.RoleExistsAsync(role);
            if (!roleExists.Result)
            {
                // ALWAYS Returns [False]
            }
        }

The initial problem came about when we were creating a new User with the UserManager, and the following method would result in an error

var roleAddResult = userManager.AddToRoleAsync(newUser, "TestRole123");

Exception Error: Role [TESTROLE123] does not exist.

Note: I can see the entry for the Role 'TestRole123' (or any other role) in the Database in the table dbo.AspNetRoles.

Any insight or help is appreciated.

Environment: Visual Studio 2017, Asp.NET Core, C#


Solution

  • One of the issues I see - you need to use keyword await in front of *Async() methods:

    var roleExists = await roleManager.RoleExistsAsync(role);
    

    and

    var roleCreated = await roleManager.CreateAsync(newRole);
    

    etc. This will remove your need to do Thread.Sleep(500); - most likely the problem is with this line.

    If you can't do async methods, use non-async versions of the methods:

    var roleCreated = roleManager.Create(newRole);