用 OWIN 中间件异常处理程序替换 Web Api 2.2 中的 IExceptionHandler

Replace IExceptionHandler in Web Api 2.2 with OWIN middleware exception handler

我创建了一个 OWIN 中间件来捕获异常。中间件除了用这样的 try catch 包装下一个调用外什么都不做

try {
  await _next(environment)
}
catch(Exception exception){
 // handle exception
}

问题是中间件没有捕获异常,因为异常是由 IExceptionHandler 的默认实现处理的,returns 一个 xml 带有堆栈跟踪。

我知道我可以用我自己的实现替换默认的 IExceptionHandler 实现,但我想要的是让 OWIN 中间件取得控制权,并忽略此默认异常处理程序或用 OWIN 中间件替换

更新:

我已将以下答案标记为答案,尽管它更像是一个 hack,但我真的相信没有 hack 就无法实现这一点,因为 WebApi 异常永远不会被 OWIN 中间件捕获,因为 Web API 处理自己的异常,而 OWIN 中间件处理中间件中引发的异常,而不是 handled/caught 这些中间件

制作一个 "ExceptionHandler : IExceptionHandler" 喜欢 in this answer。然后在 HandleCore 中,获取该异常并将其推入 OwinContext:

public void HandleCore(ExceptionHandlerContext context)
{
    IOwinContext owinContext = context.Request.GetOwinContext();
    owinContext.Set("exception", context.Exception);
}

然后在您的中间件中,检查环境是否包含 "exception" 密钥。

public override async Task Invoke(IOwinContext context)
{
    await Next.Invoke(context);

    if(context.Environment.ContainsKey("exception")) {
        Exception ex = context.Environment["exception"];
        // Do stuff with the exception
    }
}