路由在我的asp.net应用程序中不起作用

时间:2011-06-06 19:04:53

标签: asp.net-mvc-3 asp.net-mvc-routing

我有4条路线定义了5个不同的网址。使用RouteDebugger进行了大量测试,但无法解决。

问题是前2个链接始终使用 {controller} / {action} / {id} 此路由为root1且无法重定向到正确的网页。

链接

@Html.ActionLink("Go Index by name", "Page", "Home", new { name="contact"}, null)

@Html.ActionLink("Go Index by id", "Index", "Admin", new { id=2}, null)


@Html.ActionLink("Go Index by id and name", "Page", "Home", new { name = "contact", id = 2 }, null)


@Html.ActionLink("Root Admin", "Index", "Admin")


@Html.ActionLink("Root", "Index", "Home")

这是Map.Route

    routes.MapRoute("root1",
      "{controller}/{action}/{id}",
       new { controller = "Admin", action = "Index" });

    routes.MapRoute("root2",
        "{controller}/{action}/{name}",
        new { controller = "Home", action = "Page" });

    routes.MapRoute("root3", 
        "{controller}/{action}/{name}/{id}", 
        new { controller = "Home", action = "Page" });

    routes.MapRoute("root4", 
        "{controller}/{action}/{name}", 
        new { controller = "Home", action = "Index", name = UrlParameter.Optional });

2 个答案:

答案 0 :(得分:1)

为您的路线添加约束。例如:

routes.MapRoute(
    "root1",
    "{controller}/{action}/{id}",
    new { controller = "Admin", action = "Index" },
    new {id = @"\d+" }
 );

当id是整数时,将确保root1仅匹配。否则,root2会抓住它。

答案 1 :(得分:1)

这些是我设置的路线,似乎正确地击中每一条路线。

请注意,root3已移至顶部,因为root2也会与之匹配。此外,root1验证id为朱利安国王建议

路线:

@Html.ActionLink("Root Admin", "Index", "Admin")

不应与root1root2匹配,因为路径定义中分别没有idname的默认值

routes.MapRoute("root3",
     "{controller}/{action}/{name}/{id}",
      new { controller = "Home", action = "Page" });

routes.MapRoute("root1",
      "{controller}/{action}/{id}",
      new { controller = "Admin", action = "Index" },
      new { id = @"\d+" });

routes.MapRoute("root2",
      "{controller}/{action}/{name}",
      new { controller = "Home", action = "Page" });

routes.MapRoute("root4",
      "{controller}/{action}/{name}",
      new { controller = "Home", action = "Index", name = UrlParameter.Optional     
});