Owin WebApi service ignoring ExceptionFilter

牧云@^-^@ 提交于 2019-12-06 09:32:28
jumuro

You can try to implement Global Error Handling in ASP.NET Web API 2. This way you will get a global error handler for Web API middleware, but not for other middlewares in OWIN pippeline, like authorization one.

If you want to implement a globlal error handling middleware, this, this and this links could orientate you.

I hope it helps.

EDIT

Regarding on @t0mm13b's comment, I'll give a little explanation based on the first this link from Khanh TO.

For global error handling you can write a custom and simple middleware that just pass the execution flow to the following middleware in the pipeline but inside a try block.

If there is an unhandled exception in one of the following middlewares in the pipeline, it will be captured in the catch block:

public class GlobalExceptionMiddleware : OwinMiddleware
{
    public GlobalExceptionMiddleware(OwinMiddleware next) : base(next)
    { }

    public override async Task Invoke(IOwinContext context)
    {
        try
        {
            await Next.Invoke(context);
        }
        catch (Exception ex)
        {
            // your handling logic
        }
    }
}

In the Startup.Configuration() method, add the middleware in first place to the pipeline if you want to handle exceptions for all other middlewares.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use<GlobalExceptionMiddleware>();
        //Register other middlewares
    }
}

As pointed by Tomas Lycken in the second this link, you can use this to handle exceptions generated in Web API middleware creating a class that implements IExceptionHandler that just throws the captured exception, this way the global exception handler middleware will catch it:

public class PassthroughExceptionHandler : IExceptionHandler
{
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        // don't just throw the exception; that will ruin the stack trace
        var info = ExceptionDispatchInfo.Capture(context.Exception);
        info.Throw();
    }
}

And don't forget to replace the IExceptionHandler during the Web API middleware configuration:

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