我使用以下代码检查登录:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByEmailAsync(model.Email);
if (user != null)
{
if (!await UserManager.IsEmailConfirmedAsync(user.Id))
{
ViewBag.errorMessage = "You must have a confirmed email to log on.";
return View("Error");
}
}
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
当我登录时显示这个错误:Invalid login attempt.
但是电子邮件和密码已经存在。
代码:
var user = await UserManager.FindByEmailAsync(model.Email);
不是null,但是这个代码是Failure:
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
怎么了?如何解决这个问题?
如果您已经通过电子邮件找到了一个有效的用户,那么请使用找到的用户名登录。
//...
var user = await UserManager.FindByEmailAsync(model.Email);
if (user != null) {
if (!await UserManager.IsEmailConfirmedAsync(user.Id)) {
ViewBag.errorMessage = "You must have a confirmed email to log on.";
return View("Error");
}
}
var result = await SignInManager.PasswordSignInAsync(user.Username, model.Password, model.RememberMe, shouldLockout: false);
//...
在registrationConfirmation
中放置处于开发阶段的user.emailconfirmed = true
。当您迁移到生产环境时,请删除此代码。