Replace IExceptionHandler in Web Api 2.2 with OWIN middleware exception handler

浪子不回头ぞ 提交于 2019-12-04 11:09:30

问题


I have created an OWIN middleware to catch exceptions. The middleware does nothing really but wrap the next call with try catch like this

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

The problem is that the middlware is not capturing the exception because the exception is been handled by the default implementation of IExceptionHandler which returns an xml with the stack trace.

I understand that I can replace the default IExceptionHandler implementation with my own but what I want is for OWIN middleware to take control and this default exception handler to be ignored or replaced with the OWIN middleware

Update:

I have marked the below answer as an answer although it is more of a hack but I truly believe there is no way you can achieve this without a hack because WebApi exceptions will never be caught by OWIN middleware because Web API handle its own exceptions whereas OWIN middleware handles exceptions which are raised in middlewares and not handled/caught by these middlewares


回答1:


Make an "ExceptionHandler : IExceptionHandler" like in this answer. Then in HandleCore, take that exception and shove it into the OwinContext:

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

Then in your middleware, check if the Environment contains the "exception" key.

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
    }
}


来源:https://stackoverflow.com/questions/31744146/replace-iexceptionhandler-in-web-api-2-2-with-owin-middleware-exception-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!