从异常处理过滤器重定向

时间:2016-12-08 20:08:40

标签: asp.net-mvc exception-handling

我正在使用发布到Clean way to catch all errors thrown in an MVC 3.0 application?的解决方案中的过滤器,我想知道如何重定向到一个视图(位于/ Views / Account / ErrorPage中的简单错误页面,作为AccountController),在那个过滤器?它转载如下:

public class HandleExceptionsAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            var expception = filterContext.Exception;

            // Go to generic error page:

        }
    }

谢谢。

1 个答案:

答案 0 :(得分:1)

设置filterContext.Result

        filterContext.Result = new ViewResult
        {
            ViewName = "<view name>",
            ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
            TempData = filterContext.Controller.TempData
        };

这是捕获错误调用

的完整方法
    public override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);

        var controllerName = (string) filterContext.RouteData.Values["controller"];
        var actionName = (string) filterContext.RouteData.Values["action"];
        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

        filterContext.Result = new ViewResult
        {
            ViewName = "<view name>",
            ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
            TempData = filterContext.Controller.TempData
        };
        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 500;
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }