Web API OWIN启动异常处理

Dan*_*lis 6 .net c# exception asp.net-web-api owin

在我的C#Web API中,我正在尝试添加一个全局异常处理程序.我一直在使用自定义全局ExceptionFilterAttribute来处理异常并返回HttpResponseMessage:

public override void OnException(HttpActionExecutedContext context)
{
    ...

    const string message = "An unhandled exception was raised by the Web API.";
    var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError)
    {
        Content = new StringContent(message),
        ReasonPhrase = message
    };
    context.Response = httpResponseMessage;
}
Run Code Online (Sandbox Code Playgroud)

这适用于处理在控制器级别抛出的异常.

但是,在开发期间,由于数据库连接问题,我们从OWIN启动文件中抛出了错误,但是,返回了标准的IIS异常,而不是通过全局异常处理程序,并且完整的HTML被返回给我们的API使用者.

我尝试了几种不同的方法来捕获我的OWIN启动中抛出的异常:

定制ApiControllerActionInvoker:

public class CustomActionInvoker : ApiControllerActionInvoker
{
    public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        var result = base.InvokeActionAsync(actionContext, cancellationToken);

        if (result.Exception != null && result.Exception.GetBaseException() != null)
        {
            ...
        }

        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

定制ExceptionHandler:

public class CustomExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        ...

        base.Handle(context);
    }

    public override bool ShouldHandle(ExceptionHandlerContext context)
    {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

自定义OwinMiddleware组件:

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

    public override async Task Invoke(IOwinContext context)
    {
        try
        {
            await Next.Invoke(context);
        }
        catch (Exception ex)
        {
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后只使用Application_Error:

protected void Application_Error(object sender, EventArgs e)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

但似乎没有什么能够抓住这个例外.

有谁知道一种方法来捕获异常并返回一个HttpResponseMessage?或者,如果我已经尝试过的任何方法应该有效?

任何帮助非常感谢.

bik*_*868 6

我有一个可以正确执行此操作的应用程序。在我的例子中,我编写了一个中间件类,它总是返回一条消息,告诉调用者该服务不可用,因为在启动过程中出现错误。这个类FailedSetupMiddleware在我的解决方案中被调用。它的轮廓如下所示:

public class FailedSetupMiddleware
{
    private readonly Exception _exception;

    public FailedSetupMiddleware(Exception exception)
    {
        _exception = exception;
    }

    public Task Invoke(IOwinContext context, Func<Task> next)
    {
        var message = ""; // construct your message here
        return context.Response.WriteAsync(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的Configuration课程中,我有一个try...catch块来配置 OWIN 管道,仅FailedSetupMiddleware在配置期间抛出异常的情况下。

我的 OWIN 启动类如下所示:

[assembly: OwinStartup(typeof(Startup))]

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        try
        {
            //
            // various app.Use() statements here to configure
            // OWIN middleware
            //
        }
        catch (Exception ex)
        {
          app.Use(new FailedSetupMiddleware(ex).Invoke);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)