我想了解为什么会出现以下错误:
2016-02-05 12:04:16.0776 [89] FATAL ExceptionHandling.Models.EmailService + d__1.MoveNext - 发送电子邮件时出错。 - System.Net.Mail.SmtpException:发送邮件失败。 ---> System.InvalidOperationException:此时无法启动异步操作。异步操作只能在异步处理程序或模块中启动,或者在页面生命周期中的某些事件中启动。如果在执行页面时发生此异常,请确保将页面标记为<%@ Page Async =" true" %取代。此异常也可能表示尝试调用" async void"方法,在ASP.NET请求处理中通常不受支持。相反,异步方法应该返回一个Task,调用者应该等待它。 在System.Web.AspNetSynchronizationContext.OperationStarted() 在System.ComponentModel.AsyncOperation.CreateOperation(Object userSuppliedState,SynchronizationContext syncContext) 在System.Net.Mail.SmtpClient.SendAsync(MailMessage消息,对象userToken) ---内部异常堆栈跟踪结束--- 在System.Net.Mail.SmtpClient.SendAsync(MailMessage消息,对象userToken) 在System.Net.Mail.SmtpClient.SendMailAsync(MailMessage消息) 在Kubra.Common.ExceptionHandling.Models.EmailService.d__1.MoveNext()
当我运行本地时,它会生成电子邮件,当我在我的开发环境中运行时,再次没有问题。我将它移动到我的测试环境,突然间我遇到了异步问题。所有3个环境之间的配置是相同的,我试图理解潜在的问题,以便我可以解决它。
发生错误的代码:
public class EmailService : IEmailService
{
private static readonly ILogger Logger = LogFactory.GetLogger();
private readonly string _host;
private readonly int _port;
private readonly NetworkCredential _credentials;
private readonly bool _enableSsl;
public EmailService(EmailConfiguration emailSettings)
{
_host = emailSettings.Host;
_port = emailSettings.PortNumber;
_credentials = new NetworkCredential(emailSettings.Username, emailSettings.Password);
_enableSsl = emailSettings.UseSsl;
}
public async Task<bool> SendEmail(EmailTemplate email)
{
try
{
using (var client = new SmtpClient
{
Host = _host,
Port = _port,
Credentials = _credentials,
EnableSsl = _enableSsl
})
{
client.Host = _host;
client.Port = _port;
client.Credentials = _credentials;
client.EnableSsl = _enableSsl;
await client.SendMailAsync(email.Message);
return true;
}
}
catch (Exception ex)
{
Logger.Fatal(ex, "Error occurred while sending an Email.");
return false;
}
}
}
调用该类的代码:
protected void Application_Error()
{
try
{
var subject = "Server Error on MVC CSR: " + Environment.MachineName;
var email = new ErrorEmail(subject, "", serverError.StackTrace);
_emailService = new EmailService(new ConfigEmail());
Task.Run(() => { _emailService.SendEmail(email); }).Wait();
}
catch (Exception ex)
{
_logger.Fatal(ex, "Error occurred while sending e-mail");
}
}