如果出现特定异常,我想重定向用户。
为此,我编写了自定义异常过滤器,它可以工作,这意味着如果我放置一个断点,它会正确通过它,但我无法覆盖异常的正常行为并将用户移动到自定义页面。
异常模拟:
public ActionResult Index()
{
//test exception throw
throw new ArgumentNullException();
return View();
}
过滤器重定向:
public class CustomExceptionHandlerAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is ArgumentNullException)
//breakpoint here work as expected
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Home", action = "About" })
);
else
base.OnException(filterContext);
}
}
浏览器中的结果(也没有调试):
“/”应用程序中的服务器错误。
值不能为 null 或空。