我想将新注册的用户添加到应用程序中的"标准"角色。但是当我尝试注册一个新用户时,我得到了一个ArgumentNullException
_userManager.AddToRole(user.Id, "Standard");
这是我的代码
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser {
UserName = model.Email,
Email = model.Email,
PostalCode = model.PostalCode };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href="" + callbackUrl + "">here</a>");
// Gebruiker krijgt een rol toegewezen (0,4)
_userManager.AddToRole(user.Id, "Standard");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
不要忘记保存您的上下文,这可能是 id 尚未知的问题。
这个代码是我一直使用的代码。
_idManager.CreateUser(newUser, model.Password);
await _db.SaveChangesAsync();
_idManager.AddUserToRole(newUser.Id, "Standard");
await _db.SaveChangesAsync();