简体   繁体   中英

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#

I don't know how you declared your rolemanager, but following code works for me. It's configured in startup.cs and automatically creates a superuser if the roles haven't been created. Perhaps this can help you?

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

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

            //superuser
            var user = new ApplicationUser
            {
                UserName = " Name",
                Email = "Email",
                Firstname = "Firstname",
                Lastname = "Lastname"
            };
            var pass = "AwesomePasswordOverHere";
            var chkUser = await userManager.CreateAsync(user, pass);

            //make superuser 
            if (chkUser.Succeeded)
            {
                await userManager.AddToRoleAsync(user.Id, "SuperUser");
            }
        }

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM