我正在创建一个ASP.NET MVC项目,还包括密码恢复,当用户忘记密码时,他们可以重置密码。我能够发送密码重设的电子邮件,但在尝试重置resetpassword.cshtml
上的密码后,我收到一条错误消息“无效令牌”
这些是我在帐户控制器中的操作方法。
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult>
ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email,
Email = model.Email };
var result = await UserManager.CreateAsync(user,
model.Email);
System.Net.Mail.MailMessage m = new
System.Net.Mail.MailMessage(
new System.Net.Mail.MailAddress("[email protected]",
"Reset Password"),
new System.Net.Mail.MailAddress(model.Email));
m.Subject = "Reset Password";
string code = user.Id;
m.Body = string.Format("Dear {0}<BR/>Please reset your
password by clicking the following link: <a href=\"{1}\"
title=\"User Email Confirm\">{1}</a>", user.UserName,
Url.Action("ResetPassword", "Account", new { userId = user.Id,
code = code }, protocol: Request.Url.Scheme));
m.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new
System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new
System.Net.NetworkCredential("[email protected]",
"mypassword");
smtp.EnableSsl = true;
smtp.Send(m);
return RedirectToAction("ForgotPasswordConfirmation",
"Account", new { Email = user.Email });
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel
model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation",
"Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id,
model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation",
"Account");
}
AddErrors(result);
return View();
}
我不知道如何解决这个问题。
我有点同样的问题,但我希望能够用用户的用户名重置密码(我从电子邮件更改为用户名)
var user = await UserManager.FindByNameAsync(model.Email);
在这里您使用FindByNameAsync(),将其更改为FindByEmailAsync()