我尝试设置全局异常处理程序,如下所示:Web API Global Error Handling。我设置了一个在控制器构造函数中抛出异常的情况。但我的例外情况并未记录。相反,WebApi只是将异常和完整堆栈跟踪作为JSON消息返回给调用客户端。
我不知道这是否重要,但我的控制器操作正在使用async / await这样:
[HttpGet, Route("GetLocationNames")]
public async Task<IEnumerable<String>> Get()
{
return await adapter.GetLocationNames();
}
我有以下实现:
using log4net;
using System.Threading.Tasks;
using System.Web.Http.ExceptionHandling;
namespace warehouse.management.api
{
public class Log4NetExceptionLogger : ExceptionLogger
{
private ILog log = LogManager.GetLogger(typeof(Log4NetExceptionLogger));
public async override Task LogAsync(ExceptionLoggerContext context, System.Threading.CancellationToken cancellationToken)
{
log.Error("An unhandled exception occurred.", context.Exception);
await base.LogAsync(context, cancellationToken);
}
public override void Log(ExceptionLoggerContext context)
{
log.Error("An unhandled exception occurred.", context.Exception);
base.Log(context);
}
public override bool ShouldLog(ExceptionLoggerContext context)
{
return base.ShouldLog(context);
}
}
}
我正在这样注册:
using Owin;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
namespace warehouse.management.api.Config
{
public static class WebApiConfig
{
public static IAppBuilder RegisterApiConfig(this IAppBuilder app, HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Services.Add(typeof(IExceptionLogger), new Log4NetExceptionLogger());
return app;
}
}
}
这是我的packages.conf:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="4.0.20505.0" targetFramework="net45" />
<package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
<package id="Unity" version="3.5.1404.0" targetFramework="net45" />
<package id="Unity.AspNet.WebApi" version="3.5.1404.0" targetFramework="net45" />
<package id="WebActivatorEx" version="2.0" targetFramework="net45" />
</packages>
答案 0 :(得分:16)
原来这是订购。在我的启动类(未显示)中,我将调用移动到我的RegisterApiConfig方法(上面,在OP中)到我调用UseWebApi之前,现在它可以工作。