Add User to Role ASP.NET Identity

Brad Martin picture Brad Martin · Oct 30, 2013 · Viewed 100.5k times · Source

I know the new Membership includes a "Simple Role Provider."

I can't find any help related to creating a user and assigning a role when the user is created. I've added a user which created the tables on the DB correctly. I see the AspNetRoles, AspNetUserRoles, and AspNetUsers tables.

I am wanting to assign a role from AspNetRoles to a user in AspNetUsers which the ID of both the role/user are to be stored in AspNetUserRoles.

I'm stuck on the programming part of where and how to do this when I create the user.

I have a dropdown list to select the role, but using the Entity CF along with the new ASP.NET Identity model I'm not sure how to take the ID of the selectedvalue from the dropdown and the UserID and assign the role.

Answer

DmitryBoyko picture DmitryBoyko · Jan 7, 2014

I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager

But in case to provide an example so you can check it I am gonna share some default code.

First make sure you have Roles inserted.

enter image description here

And second test it on user register method.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName  };

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var currentUser = UserManager.FindByName(user.UserName); 

            var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And finally you have to get "Superusers" from the Roles Dropdown List somehow.