【问题标题】:RedirectToRoute redirects to the current action instead of redirecting to the route specified by the routenameRedirectToRoute 重定向到当前操作,而不是重定向到 routename 指定的路由
【发布时间】:2017-02-05 08:47:41
【问题描述】:

下面是我的RouteConfig.cs代码sn-p:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

    routes.MapRoute(
        name: "myroute",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "About", id = UrlParameter.Optional }
    );
}

Home/Contact 中,我重定向到名为“myroute”的路由,该路由映射到Home/About。它不是重定向到Home/About,而是重定向到相同的操作(Home/Contact)。以下是我的HomeController 代码:

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return RedirectToRoute("myroute");
    }

为什么重定向到myroute 不起作用?

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 您尚未指定操作名称,因此它使用当前请求中的值 - 您需要 return RedirectToRoute("myroute", new { action = "About" }); 或者如果您希望它转到 About 则指定路由

标签: asp.net-mvc routes url-routing asp.net-mvc-routing redirecttoroute


【解决方案1】:

当您使用RedirectToRouteHtml.RouteLinkUrl.RouteUrl 以及允许您按名称指定路由的相关方法时,该名称就像一个附加过滤器。基本上,这意味着路由只能匹配名为"myroute" 的路由,但您仍然需要提供controlleraction 和任何其他必需的路由值才能匹配该路由。

RedirectToRoute("myroute", new { controller = "Home", action = "About" })

请注意,@StephenMuecke 在评论中提供的答案也可以使用,但只能来自Home 控制器。如果未明确提供,MVC 会在生成 URL 时自动重用当前请求中的值。

附带说明,此路由配置从根本上被破坏了,因为您有 2 条路由都接受长度为 0、1、2 和 3 的路由段。基本上,虽然可以使用 myroute 生成 URL,但没有传入路由可以匹配 myroute,因为 Default 配置为始终覆盖它。这可能会导致问题,因为您打算为该路径设置的路由永远不会匹配,当您添加更多路由时,维护起来会很混乱。

有关此问题的详细信息和可能的解决方案,请参阅 Why map special routes first before common routes in asp.net mvc?

【讨论】:

    【解决方案2】:

    你可以让它更容易。使用Response.Redirect("Home/About") 但不知道有没有其他要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多