global.asax redirecttoroute不工作

时间:2013-01-31 08:36:43

标签: c# asp.net-mvc-4 global-asax custom-routes

我想在global.asax中使用自定义路由和response.redirecttoroute,但它不起作用。我在RouteConfig中有以下内容:

routes.MapRoute(
            name: "Error",
            url: "Error/{action}/{excep}",
            defaults: new { action = "Index", excep = UrlParameter.Optional }
        );

在我的global.asax中,我执行以下操作:

Response.RedirectToRoute("Error", new { action="Index", excep=ex.Message });

在我的ErrorController中,我有:

public ActionResult Index(string excep)
    {
        ViewBag.Exception = excep;

        return View();
    }

在错误的索引视图中,我调用ViewBag.Exception来显示异常。

当我使用时:

Response.Redirect("/Error/Index/0/"+ex.Message, true);

在我的控制器中使用它:

public ActionResult Index(int? id,string excep)
    {
        ViewBag.Exception = excep;

        return View();
    }

它有效,但这是默认路线,不是我想要的。为什么它可以使用重定向但不能使用redirecttoroute?

3 个答案:

答案 0 :(得分:3)

我遇到了同样的问题,但现在我找到了解决方案。也许你可以试试这个:只需根据需要重命名类名或变量名。从Global.asax更改任何内容后请注意清除浏览器缓存。希望这会有所帮助。

<强> Global.asax中

  public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
       //Make sure this route is the first one to be added
        routes.MapRoute(
           "ErrorHandler",
           "ErrorHandler/{action}/{errMsg}",
           new { controller = "ErrorHandler", action = "Index", errMsg=UrlParameter.Optional}
           );
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

一旦发生unhandles异常,就会将响应从Global.asax Application_Error事件重定向到错误处理程序

 protected void Application_Error(object sender, EventArgs e)
        {
            var errMsg = Server.GetLastError().Message;
            if (string.IsNullOrWhiteSpace(errMsg)) return;
            //Make sure parameter names to be passed is are not equal
            Response.RedirectToRoute("ErrorHandler", new { strErrMsg=errMsg });
            this.Context.ClearError();
        }

错误处理程序控制器

public class ErrorHandlerController : Controller
    {

        public ActionResult Index(string strErrMsg)
        {
            ViewBag.Exception = strErrMsg;
            return View();
        }

    }

要在HomeController的Index ActionResult上测试错误处理程序,请添加此代码。

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //just intentionally add this code so that exception will occur
            int.Parse("test");
            return View();
        }
    }

输出

enter image description here

答案 1 :(得分:2)

这个问题有一个非常好的答案:How is RedirectToRoute supposed to be used?

我会尝试在Response.End()之后添加RedirectToRoute并查看是否有效。

答案 2 :(得分:0)

这是我如何使用MVC 4解决我的问题:

<强> RouteConfig.cs

    routes.MapRoute(
            name: "ErrorHandler",
            url: "Login/Error/{code}",
            defaults: new { controller = "Login", action = "Error", code = 10000 } //default code is 10000
        );

    routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
        );

<强>的Global.asax.cs

    protected void Application_Start()
    {
            //previous code
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            this.Error += Application_Error; //register the event
    } 

    public void Application_Error(object sender, EventArgs e)
    {
            Exception exception = Server.GetLastError();
            CustomException customException = (CustomException) exception;
            //your code here

            //here i have sure that the exception variable is an instance of CustomException.
            codeErr = customException.getErrorCode(); //acquire error code from custom exception

            Server.ClearError();

            Response.RedirectToRoute("ErrorHandler", new
                                    {
                                            code = codeErr
                                    });
            Response.End();
    }

这是诀窍:确保将Response.End()放在Application_Error方法的末尾。否则,重定向到路由将无法正常工作。具体来说,代码参数不会传递给控制器​​的操作方法。

<强>的LoginController

    public class LoginController : Controller
    {
           //make sure to name the parameter with the same name that you have passed as the route parameter on Response.RedirectToRoute method.
           public ActionResult Error(int code)
           {
                   ViewBag.ErrorCode = code;

                   ViewBag.ErrorMessage = EnumUtil.GetDescriptionFromEnumValue((Error)code);

                   return View();
           }
    }
相关问题