如果遇到未处理的异常,Owin 不会发送任何响应

Owin doesn't send any response if an unhandled exception is met

如果 Owin 在应用程序中发现未处理的异常,是否可以发送带有 500 状态代码的 HTTP 响应?

对于全局错误处理,您可以编写一个自定义的简单中间件,它只将执行流传递给管道中的以下中间件,但位于 try 块内。

如果管道中的以下中间件之一存在未处理的异常,它将在 catch 块中捕获:

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, for example set HTTP status code to 500 in response
        }
    }
}

Startup.Configuration()方法中,如果要处理所有其他中间件的异常,请首先将中间件添加到管道中。

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

如果你使用WebAPI中间件,你需要实现IExceptionHandler接口并在配置中替换它。 有关详细信息,请参阅我的 response 相关问题。

希望对您有所帮助。