Owin 中间件中的 MVC 错误处理

Ide*_*ity 4 c# asp.net-mvc owin owin-middleware

当控制器中抛出某些异常时,我想捕获这些异常并执行一些额外的逻辑。

我能够通过添加到全局过滤器列表中的自定义 IExceptionFilter 来实现此目的。

但是,我更喜欢在自定义 Owin 中间件中处理这些异常。我的中间件如下所示:

      try
        {

            await Next.Invoke(context);
        }
        catch (AdalSilentTokenAcquisitionException e)
        {
           //custom logic
        }
Run Code Online (Sandbox Code Playgroud)

这段代码不起作用,看起来异常已经在 MVC 中捕获并处理了。有没有办法跳过MVC的异常处理并让中间件捕获异常?

Ide*_*ity 5

更新:我找到了一种更干净的方法,请参阅下面我更新的代码。使用这种方法,您不需要自定义异常过滤器,最重要的是,您不需要 Owin 中间件中的 HttpContext 环境服务定位器模式。

我在 MVC 中有一种工作方法,但是,不知怎的,它感觉不太舒服,所以我很欣赏其他人的意见。

首先,确保MVC的GlobalFilters中没有添加异常处理程序。

将此方法添加到全局 asax 中:

    protected void Application_Error(object sender, EventArgs e)
    {
        var lastException = Server.GetLastError();
        if (lastException != null)
        {
            HttpContext.Current.GetOwinContext().Set("lastException", lastException);
        }
    }
Run Code Online (Sandbox Code Playgroud)

重新抛出异常的中间件

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

    public override async Task Invoke(IOwinContext context)
    {
        await Next.Invoke(context);
        var exception = context.Get<Exception>("lastException");
        if (exception != null)
        {
            var info = ExceptionDispatchInfo.Capture(exception);
            info.Throw();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)