我正在编写一个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);
}
如果发生异常,则Error控制器中的Index视图显示此错误。 我现在写了以下全局过滤器:
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
例外的自定义错误视图?
答案 0 :(得分:1)
这样的事对我有用。
public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
int val = (int)(((Exception)filterContext.Exception).ActualValue);
filterContext.Result = new ViewResult
{
ViewName = "CustomError",
ViewData = new ViewDataDictionary<int>(val)
};
filterContext.ExceptionHandled = true;
}
}
}
**编辑***
public class HttpRequestValidationExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled && filterContext.Exception is HttpRequestValidationException)
{
IDictionary val = filterContext.Exception.Data;
filterContext.Result = new ViewResult
{
ViewName = "RangeError",
ViewData = new ViewDataDictionary<IDictionary>(val)
};
filterContext.ExceptionHandled = true;
}
}
}