【问题标题】:Owin doesn't send any response if an unhandled exception is met如果遇到未处理的异常,Owin 不会发送任何响应
【发布时间】:2016-05-26 10:28:39
【问题描述】:

如果 Owin 在应用程序中发现未处理的异常,有没有办法发送带有 500 状态码的 HTTP 响应?

【问题讨论】:

    标签: http asp.net-web-api owin


    【解决方案1】:

    对于全局错误处理,您可以编写一个自定义且简单的中间件,将执行流程传递给管道中的以下中间件,但在 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
        }
    }
    

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

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2015-04-25
      • 1970-01-01
      • 2014-03-06
      相关资源
      最近更新 更多