且构网

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

捕捉的ASP.NET Web API的所有未处理的异常

更新时间:2023-02-15 12:47:17

这是现在可能有2.1的WebAPI(请参阅What's新):

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