问题描述
如何捕获所有发生在 ASP.NET Web Api 中的未处理异常,以便我可以记录它们?
How do I catch all unhandled exceptions that occur in ASP.NET Web Api so that I can log them?
到目前为止我已经尝试过:
So far I have tried:
- 创建并注册
异常处理属性
- 在
Global.asax.cs
中实现一个 - 订阅
AppDomain.CurrentDomain.UnhandledException
- 订阅
TaskScheduler.UnobservedTaskException
Application_Error
方法ExceptionHandlingAttribute
成功处理了在控制器动作方法和动作过滤器中抛出的异常,但不处理其他异常,例如:
The ExceptionHandlingAttribute
successfully handles exceptions that are thrown within controller action methods and action filters, but other exceptions are not handled, for example:
- 操作方法返回的
IQueryable
执行失败时抛出的异常 - 消息处理程序抛出的异常(即
HttpConfiguration.MessageHandlers
) - 创建控制器实例时抛出的异常
- Exceptions thrown when an
IQueryable
returned by an action method fails to execute - Exceptions thrown by a message handler (i.e.
HttpConfiguration.MessageHandlers
) - Exceptions thrown when creating a controller instance
基本上,如果异常将导致 500 Internal Server Error 返回给客户端,我希望将其记录下来.实施 Application_Error
在 Web Forms 和 MVC 中做得很好 - 我可以在 Web Api 中使用什么?
Basically, if an exception is going to cause a 500 Internal Server Error to be returned to the client, I want it logged. Implementing Application_Error
did this job well in Web Forms and MVC - what can I use in Web Api?
推荐答案
WebAPI 2.1 现在可以做到这一点(请参阅 新增功能):
This is now possible with WebAPI 2.1 (see the What's New):
创建一个或多个 IExceptionLogger 的实现.例如:
Create one or more implementations of IExceptionLogger. For example:
public class TraceExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
Trace.TraceError(context.ExceptionContext.Exception.ToString());
}
}
然后在您的应用程序的 HttpConfiguration 中注册,在配置回调中,如下所示:
Then register with your application's HttpConfiguration, inside a config callback like so:
config.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());
或直接:
GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());
这篇关于捕获 ASP.NET Web Api 中所有未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!