更新:我发现一个更清洁的方法,请参阅下面我更新的代码。 使用这种方法,您不需要自定义的Exception Filter,最重要的是,您不需要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();
}
}
}
的[在ASP.NET如何禁用\ *所有\ *异常处理可能的复制Web API 2(为我自己腾出空间)?](http://stackoverflow.com/questions/34201527/how-do-i-disable-all-exception-handling-in-asp-net-web-api- 2-to-make-room-for) –
不重复 - 另一个问题是关于Web API 2,这是关于MVC框架的。部分答案(OWIN中间件)适用,但关闭默认错误处理的机制不同。 –