我正在使用默认的ASP.net“注册”方法从另一个控制器创建新用户:
public async Task<ActionResult> SyncNewUsers()
{
RegisterViewModel register = new RegisterViewModel();
register.UserName = item.entity_name;
register.Email = item.fields.preferred_email;
register.MobilePhone = item.fields.preferred_phone;
register.Password = "IT@test123";
register.ConfirmPassword = "IT@test123";
register.Role = "Admin";
await new AccountController().RegisterNewUser(register);
return View();
}
我的“注册”方法:
public async Task<ActionResult> RegisterNewUser(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, PhoneNumber = model.MobilePhone };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await this.UserManager.AddToRoleAsync(user.Id, model.Role);
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("newxpusers", "Users");
}
AddErrors(result);
}
return View(model);
}
但是,它从来没有超过var result = await UserManager.CreateAsync(user, model.Password);
的错误提示:'UserManager'抛出了'system.nullreferenceexception'类型的异常
我认为这与UserManager中的HttpContext有关,但是我不确定在将模型即时传递给此方法而不是通过标准表单提交时如何处理。
答案 0 :(得分:0)
通过实施以下操作最终绕过UserManager.CreateAsync(user, model.Password);
:
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var result = await manager.CreateAsync(user, model.Password);