C# MVC 全局错误处理:Application_Error 未触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/719329/
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-04 22:22:51  来源:igfitidea点击:

MVC Global error handling: Application_Error not firing

c#asp.net-mvcerror-handling

提问by Dan

I am attempting to implement global error handling in my MVC application.

我正在尝试在我的 MVC 应用程序中实现全局错误处理。

I have some logic inside my Application_Errorthat redirects to an ErrorControllerbut it's not working.

我的内部有一些逻辑Application_Error重定向到 anErrorController但它不起作用。

I have a break point inside my Application_Errormethod in the the Global.aspx.

我的Application_Error方法中有一个断点在Global.aspx.

When I force an exception the break point is not being hit. Any ideas why?

当我强制异常时,断点没有被击中。任何想法为什么?

采纳答案by Konstantin Tarkus

You can try this approach for testing:

您可以尝试这种方法进行测试:

protected void Application_Error(object sender, EventArgs e)
{
    var error = Server.GetLastError();
    Server.ClearError();
    Response.ContentType = "text/plain";
    Response.Write(error ?? (object) "unknown");
    Response.End();
}

Web.config

网页配置

<customErrors mode="Off" />

回答by Steve

I can't tell you for sure what's wrong, but I can think of a couple of things to check... firstly, is VS breaking on the exception? If you are in the debugger this is the default I think. If it is just hit F5 until you get to your code with the breakpoint. Also, are you sure you don't handle the exception anywhere before it gets to Application_Error?

我不能肯定地告诉你出了什么问题,但我可以想到一些要检查的事情......首先,VS 是否打破了异常?如果您在调试器中,这是我认为的默认设置。如果它只是按 F5,直到您使用断点到达您的代码。另外,您确定在异常发生之前没有在任何地方处理异常Application_Error吗?

Another thing to check - CustomErrorsmode in web.config, this is set to Off, right?

另一件事要检查 - CustomErrorsweb.config 中的模式,这被设置为Off,对吗?

回答by tvanfosson

I think a better way to handle this would be using the HandleErrorAttributeto decorate your controller (perhaps a base controller). This would give you the option to do logging or handle errors in different controllers with different errors by extending this attribute and modifying it to fit your needs, say by changing the view that gets rendered. Using this attribute uses the standard filter processing in MVC and builds the page using views rather than writing directly to the response as you might do using Application_Error.

我认为处理这个问题的更好方法是使用HandleErrorAttribute来装饰您的控制器(可能是一个基本控制器)。这将使您可以选择通过扩展此属性并修改它以满足您的需要(例如通过更改呈现的视图)来记录或处理具有不同错误的不同控制器中的错误。使用此属性使用 MVC 中的标准过滤器处理并使用视图构建页面,而不是像使用 Application_Error 那样直接写入响应。