【问题标题】:MVC error handling in Owin MiddlewareOwin 中间件中的 MVC 错误处理
【发布时间】:2017-04-07 18:26:02
【问题描述】:

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

我能够通过添加到全局过滤器列表的自定义 IExceptionFilter 来实现这一点。

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

      try
        {

            await Next.Invoke(context);
        }
        catch (AdalSilentTokenAcquisitionException e)
        {
           //custom logic
        }

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

【问题讨论】:

标签: c# asp.net-mvc owin owin-middleware


【解决方案1】:

没有完美方法可以做到这一点(据我所知),但您可以将默认的IExceptionHandler 替换为仅将错误传递到堆栈其余部分的方法。

我为此做了some extensive digging,目前似乎真的没有更好的方法。

【讨论】:

  • 感谢您的回复,但是我使用的是 MVC 而不是 Web Api,所以我替换了 config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());与 GlobalFilters.Filters.Add(new MyExceptionHandler());这样,中间件就不会处理异常了……我应该如何在MVC中配置MyExceptionHandler?
  • @Identity: MVC 在 ASP.NET Core 1.0 中?还是像 pre-Core MVC 框架一样?
  • 我使用的是 Asp.net MVC 5, (.NET 4.6)
  • 你觉得我下面的方法怎么样?你有什么顾虑吗?
【解决方案2】:

更新:我找到了一种更简洁的方法,请参阅下面的更新代码。 使用这种方法,您不需要自定义异常过滤器,最重要的是,您不需要 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);
        }
    }

重新抛出异常的中间件

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();
        }
    }
}

【讨论】:

  • 您不需要将异常从 Application_Error 添加到 OwinContext。从 MVC 控制器抛出的任何异常都将添加到 HttpContext.AllErrors。您可以从 IOwinContext 检索 HttpContextBase,然后处理它包含的所有错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
相关资源
最近更新 更多