[英]Adding role to user after registration MVC5
I want to add newly registered user to a "Standard" role in my application. 我想将新注册的用户添加到应用程序中的“标准”角色。 But when I try to register a new user I get an ArgumentNullException
on _userManager.AddToRole(user.Id, "Standard");
但是,当我尝试注册新用户时,我在_userManager.AddToRole(user.Id, "Standard");
上收到ArgumentNullException
_userManager.AddToRole(user.Id, "Standard");
This is my code 这是我的代码
// 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);
}
Don't forget to save your context, this might be the issue that an id is not known yet. 不要忘记保存上下文,这可能是一个未知的问题。
This code is the one I allways use. 这段代码是我一直使用的代码。
_idManager.CreateUser(newUser, model.Password);
await _db.SaveChangesAsync();
_idManager.AddUserToRole(newUser.Id, "Standard");
await _db.SaveChangesAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.