且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

捕获 ASP.NET Web Api 中所有未处理的异常

更新时间:2023-02-15 12:38:48

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());