我有以下代码可以尝试在注册后自动记录用户,但由于某种原因它不起作用。
代码登上了行:
return RedirectToAction("Index", "Home");
,但由于某种原因仍未登录用户。我认为Signinasync会做到。
有人知道为什么它不会自动记录用户?
// 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,
FirstName = model.FirstName,
LastName = model.LastName,
PasswordHint = model.PasswordHint,
EmailConfirmed = true
};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, false);
UserManager.AddToRole(user.Id, AppConstants.Roles.Candidate);
//create a candidate profile for this candidate.
ApplicationDbContext context = new ApplicationDbContext();
var savedUser = context.Users.Single(x => x.Email == user.Email);
savedUser.Candidate = new Candidate();
try
{
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type "{0}" in state "{1}" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: "{0}", Value: "{1}", Error: "{2}"",
ve.PropertyName,
eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
ve.ErrorMessage);
}
}
throw;
}
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
添加或更改角色或主张时,在调用UserManager.Update(user);
之前,UserManager
不会自动持续这些更改。