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.
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.
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.
I had the same challenge. This is the solution I found to add users to roles.
internal class Security
{
ApplicationDbContext context = new ApplicationDbContext();
internal void AddUserToRole(string userName, string roleName)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
try
{
var user = UserManager.FindByName(userName);
UserManager.AddToRole(user.Id, roleName);
context.SaveChanges();
}
catch
{
throw;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With