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