【问题标题】:global.asax redirecttoroute not workingglobal.asax 重定向路由不起作用
【发布时间】:2013-01-15 07:13:37
【问题描述】:

我想在我的 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?

【问题讨论】:

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


    【解决方案1】:

    另一个问题有一个很好的答案:How is RedirectToRoute supposed to be used?

    我会尝试在RedirectToRoute 之后添加一个Response.End(),看看是否可行。

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,但现在我找到了解决方案。也许你可以试试这个:只需根据你的需要重命名类名或变量名。从 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();
              }
          }
      

      输出将是

      【讨论】:

      • 您是否尝试清除浏览器缓存?也可以在不同的浏览器中尝试。该解决方案正在运行,我们现在正在使用它。跟踪所有异常非常有用
      • 我终于让它工作了。我不得不在我的 global.asax 中为我的错误路由再次指定我的控制器和操作。所以我有: Response.RedirectToRoute("Error", new { controller="Error",action="Index",ex = excep });感谢您的帮助!
      【解决方案3】:

      这是我使用 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 方法的末尾。否则,重定向到路由将无法正常工作。具体来说,代码参数不会传递给控制器​​的action方法。

      登录控制器

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-24
        • 2017-09-17
        • 2019-01-19
        • 2016-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多