【发布时间】:2013-12-05 02:08:22
【问题描述】:
如果出现未处理的错误,我想向管理员发送一封电子邮件,其中包含发生错误的信息。以下是我的 web.config 和 Global.asax.cs 文件中的内容,重定向有效,但电子邮件无效:
<system.web>
<customErrors mode="On" defaultRedirect="error.aspx" />
</system.web>
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the exception object.
Exception error = Server.GetLastError();
MailMessage mail = new MailMessage();
mail.To.Add("admin@mysite.com");
mail.Subject = "Error";
mail.Body = "Somebody has experienced an error." + "<br><br>";
mail.Body += error.ToString();
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("username", "password");
smtp.Port = 587;
smtp.Send(mail);
Server.ClearError();
}
【问题讨论】:
-
“电子邮件无法正常工作”的原因是什么?请更具体。
-
你在
smtp.Send(mail);上没有异常吗? -
邮件没有发送,除了error.aspx页面的默认信息外,没有显示任何错误信息。看起来好像应用程序重定向到错误页面并且对 Global.asax 什么都不做。
-
您能否在 Server.GetLastError() 之后立即检查您的 var 错误是否为 null,这样可以避免 error.ToString() 上的 null 异常。也尝试删除 defaultRedirect。
-
我找到了这个,它解决了我的问题,至少现在是这样:stackoverflow.com/questions/343014/…
标签: c# asp.net unhandled-exception