异步电子邮件发送不返回视图
本文关键字:返回 视图 电子邮件 异步 | 更新日期: 2023-09-27 18:30:56
我的 Asp.net 网站上的忘记密码电子邮件链接有问题。
基本上,一切正常,它会向帐户发送电子邮件,密码可以重置,但我收到 404 错误而不是返回正确的页面。
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null) // || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// 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.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href='"" + callbackUrl + "'">here</a>");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
我认为这是这条线的问题:
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href='"" + callbackUrl + "'">here</a>");
如果没有此行,它将返回正确的视图,但显然电子邮件不会发送。我已经调试并逐步完成它,但找不到任何错误。
还有其他人遇到过这种情况吗?
提前致谢
注意:如果模型为空,则返回正确的视图
编辑:标识消息
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
var mailMessage = new MailMessage("Email here",
message.Destination,
message.Subject,
message.Body
);
var client = new SmtpClient();
client.SendAsync(mailMessage, null);
return Task.FromResult(0);
}
在电子邮件部分中,您应该会收到此错误"异步模块或处理程序已完成,而异步操作仍处于挂起状态"。我相信你得到404是因为可能没有找到错误页面。
您可以尝试以下操作
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
var mailMessage = new MailMessage("Email here",
message.Destination,
message.Subject,
message.Body
);
var client = new SmtpClient();
return client.SendMailAsync(mailMessage);
}
或使用等待/异步方式
public async Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
var mailMessage = new MailMessage("Email here",
message.Destination,
message.Subject,
message.Body
);
var client = new SmtpClient();
await client.SendMailAsync(mailMessage);
}