处理ASP.NET应用程序的global.asax中的Application_Error

Han*_*nan 26 asp.net

我希望在应用程序崩溃时向管理员发送邮件.所以我只是这样做global.asax:

void Application_error(object sender, EventArgs e)
{
    SendMessageToAdministarator(Server.GetLastError().ToString());
}
Run Code Online (Sandbox Code Playgroud)

但实际上很多次都Application_Error被调用,即使应用程序不会崩溃.

我希望在应用程序崩溃时只向管理员发送邮件.

另外,我有一个简单的方法来重新启动应用程序吗?

我正在寻找最简单的解决方案.

rsl*_*ite 55

应用程序未崩溃时会发送什么样的错误?您可以检查异常的类型,并且不发送有关不会使应用程序崩溃的异常的电子邮件(例如,重定向可以抛出我在代码中手动过滤的ThreadAbortException):

protected void Application_Error(Object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    if (ex is ThreadAbortException)
        return;
    Logger.Error(LoggerType.Global, ex, "Exception");
    Response.Redirect("unexpectederror.htm");
}
Run Code Online (Sandbox Code Playgroud)

您可以向错误页面添加重定向,其中包含用户发生错误的消息以及指向站点中相关页面的链接.这是为了"重新启动应用程序" - 我希望这是你想要的.

此外,您可能会考虑使用log4net进行日志记录,这也可以记录服务器上的错误发送有关错误的电子邮件.