Why does a role shows as “not exist” even when pre

2019-02-27 09:58发布

问题:

I'm trying to add users to a role when registering a user so i seeded the roles and updated the database with the code below in the migrations.cs class

        var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        string[] roleNames = { "Admin", "Reviewer", "User" };
        IdentityResult roleResult;
        foreach (var roleName in roleNames)
        {
            if (!RoleManager.RoleExists(roleName))
            {
                roleResult = RoleManager.Create(new IdentityRole(roleName));
            }
        }

i tried to fetch the roleNames into a dropdownlist in my accountcontroller class

public ActionResult Register()
{
    var model = new RegisterViewModel();
        model.RolesList = new SelectList(_db.Roles, "Id", "Name");

    return View(model);
}

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser()
        {
            UserName = model.UserName,
            PortalUser = new PortalUser()
            {
                Email = model.Email,
                UserName = model.UserName
            }
        };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            UserManager.AddToRole(user.Id, model.Roleid);                
            return RedirectToAction("Index", "ApplicationReview");
        }
        else
        {
            AddErrors(result);
        }
    }
    model.RolesList = new SelectList(_db.Roles, "Id", "Name");
    // If we got this far, something failed, redisplay form
    return View(model);
}

However the debugger showed an error at this point

UserManager.AddToRole(user.Id, model.Roleid); Role bec759ac-55ca-40f0-a8b8-00de314dd2b3 does not exist.

however this role exist in the database so i'm confused as to what the problem is

回答1:

The second parameter is the string role, as in "Reviewer" not the id of the role. It's erroring out because there is literally no role with Name equal to that GUID.

See: https://msdn.microsoft.com/en-us/library/dn497483(v=vs.108).aspx