gpt4 book ai didi

c# - 发送带有 Global.asax 文件的电子邮件

转载 作者:行者123 更新时间:2023-11-30 18:31:29 25 4
gpt4 key购买 nike

如果出现未处理的错误,我想向管理员发送一封电子邮件,其中包含所发生错误的信息。以下是我的 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();
}

最佳答案

您应该安装 Elmah 而不是自己滚动(您可以通过 NuGet 完成)并让它为您完成工作。最好的代码是您不编写的代码。

Elmah 是一个 HttpModule,它位于 ASP.Net 堆栈之上并捕获/处理未捕获的异常:

ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code:

  • Logging of nearly all unhandled exceptions.
  • A web page to remotely view the entire log of recoded exceptions.
  • A web page to remotely view the full details of any one logged exception, including colored stack traces.
  • In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
  • An e-mail notification of each error at the time it occurs.
  • An RSS feed of the last 15 errors from the log.

配置 Elmah 发送电子邮件(在记录邮件之上)非常简单

如果你打算自己写,安装Log4Net并将其配置为使用 1 个或多个 SMTP appenders除了你想要/需要/想要的任何其他日志附加程序。

关于c# - 发送带有 Global.asax 文件的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20106842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com