Web API OWIN启动exception处理

在我的C#Web API中,我正在尝试添加一个全局exception处理程序。 我一直在使用自定义全局ExceptionFilterAttribute来处理exception并返回一个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; } 

这适用于处理控制器级别抛出的exception。

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

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

自定义ApiControllerActionInvoker

 public class CustomActionInvoker : ApiControllerActionInvoker { public override Task InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { var result = base.InvokeActionAsync(actionContext, cancellationToken); if (result.Exception != null && result.Exception.GetBaseException() != null) { ... } return result; } } 

自定义ExceptionHandler

 public class CustomExceptionHandler : ExceptionHandler { public override void Handle(ExceptionHandlerContext context) { ... base.Handle(context); } public override bool ShouldHandle(ExceptionHandlerContext context) { return true; } } 

自定义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) { ... } } } 

最后只使用Application_Error

 protected void Application_Error(object sender, EventArgs e) { ... } 

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

有没有人知道捕获exception并返回HttpResponseMessage ? 或者,如果我已经尝试过的任何方法应该有效?

任何帮助非常感谢。

我有一个正确执行此操作的应用程序。 在我的例子中,我编写了一个中间件类,它始终返回一条消息,告诉调用者该服务不可用,因为启动时出错。 这个类在我的解决方案中称为FailedSetupMiddleware 。 它的轮廓看起来像这样:

 public class FailedSetupMiddleware { private readonly Exception _exception; public FailedSetupMiddleware(Exception exception) { _exception = exception; } public Task Invoke(IOwinContext context, Func next) { var message = ""; // construct your message here return context.Response.WriteAsync(message); } } 

在我的Configuration类中,我有一个try...catch块,在配置期间抛出exception的情况下,仅使用FailedSetupMiddleware配置OWIN管道。

我的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); } } }