ASP.NET MVC URL Routing with Multiple Route Values

為{幸葍}努か 提交于 2019-11-29 18:59:46

It is using the first route that is fully satisfied. Try putting your SlugsAfterId route above the Default one.

It's basically going: "Check Default. Got an action? Yes. Got an id? Yes. Use this one and chuck any other parameters in the querystring."

As a side note, doing that will make your Default route redundant as you provide a default value for the slug parameter.

MunkiPhD

Garry (above) is correct. You can use Mr. Haack's route debugger for MVC. It can help resolve routing issues by showing you which routes are hit and when.

Here is the Blog Post. And here is the Zip File.

You could add a Constraint to your Routes that contain "id" since it's presumably only to accept a number. This way the first route will only match when the "id" is numeric, then it would make the second route for all other values. Then place the one that includes the {slug} at the top and everything should work correctly.

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 = "" }
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!