我有一个发送简单电子邮件的Action:
[HttpPost, ActionName("Index")]
public ActionResult IndexPost(ContactForm contactForm)
{
if (ModelState.IsValid)
{
new EmailService().SendAsync(contactForm.Email, contactForm.Name, contactForm.Subject, contactForm.Body, true);
return RedirectToAction(MVC.Contact.Success());
}
return View(contactForm);
}
还有一个邮件服务:
public void SendAsync(string fromEmail, string fromName, string subject, string body, bool isBodyHtml)
{
MailMessage mailMessage....
....
SmtpClient client = new SmtpClient(settingRepository.SmtpAddress, settingRepository.SmtpPort);
client.EnableSsl = settingRepository.SmtpSsl;
client.Credentials = new NetworkCredential(settingRepository.SmtpUserName, settingRepository.SmtpPassword);
client.SendCompleted += client_SendCompleted;
client.SendAsync(mailMessage, Tuple.Create(client, mailMessage));
}
private void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
Tuple<SmtpClient, MailMessage> data = (Tuple<SmtpClient, MailMessage>)e.UserState;
data.Item1.Dispose();
data.Item2.Dispose();
if (e.Error != null)
{
}
}
当我发送邮件时,使用Async方法,然后我的SendAsync方法立即返回,然后调用RedirectToAction。但是ASP.NET在client_SendCompleted完成之前不会发送响应(在这种情况下是重定向)。我想要理解的是:当在Visual Studio调试器中观察执行时,SendAsync立即返回(并调用RedirectToAction),但在邮件发送完成之前,浏览器上什么都不会发生?
如果我在client_SendCompleted内设置断点,客户端会一直处于加载状态,直到我在调试器中按F5。