具有多个路由值的ASP.NET MVC URL路由

Ian*_*ley 50 asp.net asp.net-mvc url-routing

当我有一个需要多个参数的路由时,我遇到了Html.ActionLink的问题.例如,给定我的Global.asax文件中定义的以下路由:

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}.mvc/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

routes.MapRoute(
    "Tagging",
    "{controller}.mvc/{action}/{tags}",
    new { controller = "Products", action = "Index", tags = "" }
);

routes.MapRoute(
    "SlugsAfterId",
    "{controller}.mvc/{action}/{id}/{slug}",
    new { controller = "Products", action = "Browse", id = "", slug = "" }
);
Run Code Online (Sandbox Code Playgroud)

前两条路线没有问题,但是当我尝试使用以下方法创建到第三条路线的动作链接时:

<%= Html.ActionLink(Html.Encode(product.Name), "Details", new { id = product.ProductId, slug = Html.Encode(product.Name) }) %>
Run Code Online (Sandbox Code Playgroud)

我最终得到了像[site-root]/Details/1?slug = url-slug这样的网址,而我希望网址更像是[site-root]/Details/1/url-slug

任何人都可以看到我错在哪里?

Gar*_*ler 60

它使用的是完全满意的第一条路线.尝试将您的SlugsAfterId路线置于Default一个路线之上.

它基本上是:"检查默认值.有一个动作吗?是的.有一个id?是的.使用这一个并查询查询字符串中的任何其他参数."

作为旁注,这样做会使您的Default路由冗余,因为您为slug参数提供了默认值.


Mun*_*PhD 32

加里(上图)是正确的.您可以将Haack先生的路由调试器用于MVC.它可以通过显示命中哪些路由以及何时路由来解决路由问题.

这是Blog Post.这是Zip文件.

  • +1为路由调试器的链接 - 谢谢 (6认同)

Chr*_*ann 8

您可以在包含"id"的路由中添加约束,因为它可能只接受一个数字.这样,第一条路线只会在"id"为数字时匹配,然后它将为所有其他值制作第二条路线.然后将包含{slug}的那个放在顶部,一切都应该正常工作.

routes.MapRoute(
    "SlugsAfterId",
    "{controller}.mvc/{action}/{id}/{slug}",
    new { controller = "Products", action = "Browse", id = "", slug = "" },
    new { id = @"\d+" }
);

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}.mvc/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" },  // Parameter defaults
    new { id = @"\d+" }
);

routes.MapRoute(
    "Tagging",
    "{controller}.mvc/{action}/{tags}",
    new { controller = "Products", action = "Index", tags = "" }
);
Run Code Online (Sandbox Code Playgroud)