C# 如果打开自定义错误,是否不会触发 global.asax Application_Error 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12111387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:06:33  来源:igfitidea点击:

Is global.asax Application_Error event not fired if custom errors are turned on?

c#.netasp.net-mvc

提问by jcvandan

If you have custom errors set to RemoteOnlyin web config - does this mean that MVC's application level error event in global.asax- Application_Erroris not fired on error?

如果您RemoteOnly在 web 配置中设置了自定义错误- 这是否意味着 MVC 的应用程序级错误事件global.asax-Application_Error不会因错误而触发?

I have just noticed that when a certain error occurs in my application, and I am viewing the site remotely, no error is logged. However, when I am accessing the app on the server and the same error occurs, the error is logged.

我刚刚注意到,当我的应用程序中出现某个错误并且我正在远程查看站点时,没有记录任何错误。但是,当我访问服务器上的应用程序并发生相同的错误时,会记录该错误。

this is the custom errors config setting:

这是自定义错误配置设置:

<customErrors defaultRedirect="/Error/Application" mode="RemoteOnly">
    <error statusCode="403" redirect="/error/forbidden"/>
    <error statusCode="404" redirect="/error/notfound"/>
    <error statusCode="500" redirect="/error/application"/>
</customErrors>

EDIT

编辑

Just out of interest for people - I ended up completely turning off custom errors and dealing with redirection in Application_Errorlike so:

只是出于人们的兴趣 - 我最终完全关闭了自定义错误并Application_Error像这样处理重定向:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();

    // ... log error here

    var httpEx = exception as HttpException;    

    if (httpEx != null && httpEx.GetHttpCode() == 403)
    {
        Response.Redirect("/youraccount/error/forbidden", true);
    }
    else if (httpEx != null && httpEx.GetHttpCode() == 404)
    {
        Response.Redirect("/youraccount/error/notfound", true);
    }
    else
    {
        Response.Redirect("/youraccount/error/application", true);
    }
}

采纳答案by Josh

If you do not call Server.ClearError or trap the error in the Page_Error or Application_Error event handler, the error is handled based on the settings in the section of the Web.config file.

如果您不调用 Server.ClearError 或在 Page_Error 或 Application_Error 事件处理程序中捕获错误,则会根据 Web.config 文件部分中的设置处理错误。

See this SO questionfor more information

有关更多信息,请参阅此 SO 问题