全局.asax的redirecttoroute不起作用

3

我希望在我的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();
    }

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

当我使用以下代码:

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

然后在我的控制器中使用:

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

        return View();
    }

它能够工作,但这是使用默认路由而非我想要的。为什么重定向可以正常工作,但重定向到路由却不行?

3个回答

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
        );

    }

一旦发生未处理的异常,请从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

你尝试清除浏览器缓存了吗?也可以在不同的浏览器中尝试。那个解决方案正在发挥作用,我们现在正在使用它。跟踪所有异常非常有用。 - Jobert Enamno
终于搞定了。我不得不在我的global.asax中再次指定我的控制器和操作以便于我的错误路由。所以我有: Response.RedirectToRoute("Error", new { controller="Error",action="Index",ex = excep });感谢您的帮助! - Jurgen Vandw

3
这个问题的另一个答案非常好:如何使用RedirectToRoute? 我建议在RedirectToRoute之后加上Response.End(),看看这是否有效。

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();
    }

这里有个诀窍:确保在Application_Error方法的末尾放置Response.End()。否则,重定向到路由将无法正常工作。具体来说,代码参数将无法传递给控制器的操作方法。 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();
           }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接