我正在编写一个 MVC 5 互联网应用程序,并且对HttpRequestValidationException
异常有疑问。
我之前在控制器中的代码如下:
protected override void OnException(ExceptionContext filterContext)
{
// Make use of the exception later
this.Session["ErrorException"] = filterContext.Exception;
if (filterContext.Exception is HttpRequestValidationException)
{
TempData["UITitle"] = "Validation";
TempData["UIHeading"] = customErrorType;
TempData["UIMessage"] = filterContext.Exception.Message;
TempData["UIException"] = filterContext.Exception;
filterContext.ExceptionHandled = true;
}
else
{
TempData["UITitle"] = "Error";
TempData["UIHeading"] = customErrorType;
TempData["UIMessage"] = filterContext.Exception.Message;
TempData["UIException"] = filterContext.Exception;
}
filterContext.Result = this.RedirectToAction("Index", "Error");
base.OnException(filterContext);
}
如果发生异常,则错误控制器中的索引视图会显示此错误。我现在编写了以下全局过滤器:
public class ExceptionFilterDisplayErrorView : IExceptionFilter
{
public virtual void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
RouteValueDictionary routeValueDictionary = new RouteValueDictionary();
routeValueDictionary.Add("controller", "Error");
routeValueDictionary.Add("action", "Index");
filterContext.Controller.TempData.Clear();
filterContext.Controller.TempData.Add("UITitle", "Error");
filterContext.Controller.TempData.Add("UIHeading", "Error");
filterContext.Controller.TempData.Add("UIMessage", filterContext.Exception.Message);
filterContext.Controller.TempData.Add("UIException", filterContext.Exception);
RedirectToRouteResult redirectToRouteResult = new RedirectToRouteResult(routeValueDictionary);
filterContext.Result = redirectToRouteResult;
}
}
上述过滤器的工作方式与之前的OnException
功能相同,除了现在,如果发生HttpRequestValidationException
异常,将显示默认堆栈跟踪页面,而不是错误控制器视图。
HttpRequestValidationException
是否可以在异常过滤器中显示异常的自定义错误视图?