我寻找一种通用方式来显示抛出的异常,而不重定向到错误页面,而是在同一个视图中显示它。我在下面尝试了这些:
1)我首先尝试通过在 global.asax 中添加自定义过滤器并public override void OnException(ExceptionContext filterContext)
在我的 Attribute 类中覆盖来处理它们,但这样,我无法以我想要的方式填充 filterContext.Result,因为视图的旧模型不是可达,所以我只能重定向到错误页面,但这不是我想要的。
2)然后我试图在我的BaseController
(我的所有控制器都继承自它)上捕获异常。我再次public override void OnException(ExceptionContext filterContext)
在我的控制器中覆盖并将异常详细信息等放入 ViewBag 并将页面重定向到相同的视图,filterContext.HttpContext.Response.Redirect(filterContext.RequestContext.HttpContext.Request.Path );
但 ViewBag 内容在重定向页面中丢失了,所以我想不出任何其他方式?
我怎样才能做到这一点?我写的代码示例BaseController
如下:
protected override void OnException(ExceptionContext filterContext) {
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
//filterContext.Result = new ViewResult
//{
// ViewName = actionName,
// ViewData = new ViewDataDictionary<??>(??),
// TempData = filterContext.Controller.TempData,
//};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
ModelState.AddModelError("Error", filterContext.Exception.Message);
ViewBag.das = "dasd";
filterContext.HttpContext.Response.Redirect(filterContext.RequestContext.HttpContext.Request.Path);
}