Global.asax(MVC)中的应用程序错误重定向到错误页面失败

时间:2015-07-08 09:08:57

标签: asp.net-mvc visual-studio-2010 asp.net-mvc-3 global-asax

在Global.asax中遇到应用程序错误时,我很难尝试重定向到我的错误处理控制器。

这是我的RouteCollection

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

    routes.MapRoute(
        "DefaultError",
        "{controller}/{action}/{id}",
        new { controller = "HndlError", action = "AllErrors", id = UrlParameter.Optional }
        );

我的Global.asax Application_Error有此

                this.Context.Response.Clear();
                this.Context.ClearError();
                //this.Response.Redirect("~/HndlError/AllErrors") // This one Works !!!


                this.Response.RedirectToRoute( new { controller = "HndlError",
 action = "AllErrors", id = ErrorMessage }); // This does not Work

                this.Response.End();

我的控制器操作在使用Response.Redirect时确实受到了影响,但返回了一个RedirectToRoute的空白页面。做了一些搜索,然后遇到了这个创业板!

Beware of ResponseRedirectToRoute in MVC 3

这是否意味着它在MVC3中不起作用或我错过了什么?请帮助。

感谢

1 个答案:

答案 0 :(得分:2)

尝试以下方法:

protected void Application_Error(object sender, EventArgs e)
{
    HttpContext ctx = HttpContext.Current;
    ctx.Response.Clear();
    RequestContext rc =((MvcHandler)ctx.CurrentHandler).RequestContext;
    rc.RouteData.Values["action"] = "AllErrors";

    rc.RouteData.Values["controller"] = "HndlError";
    rc.RouteData.Values["id"] = ErrorMessage ;

    IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
    IController controller = factory.CreateController(rc, "HndlError");
    controller.Execute(rc);
    ctx.Server.ClearError();
}