简体   繁体   English

ASP.NET MVC路由,根据字符串数重定向到控制器

[英]ASP.NET MVC Routes, redirect to controller depending on number of strings

I have a small site I am working on where I need to have 3 different routes such as: 我在一个小型网站上工作,因此需要3条不同的路线,例如:

  1. .com/id/foo .com / id / foo

2 .com/id/foo/bar 2 .com / id / foo / bar

3 .com/id/foo/bar/user 3 .com / id / foo / bar / user

So number 1 would be for the id of foo. 因此,数字1将代表foo的ID。 Route 2 would be the id of bar. 路线2将是bar的ID。 Finally route 3 would be the id of the user. 最后,路由3将是用户的ID。

How would I set the routes up to do this? 我将如何设置路线来做到这一点?

If all of those map to a single controller and action, you can accomplish it like this: 如果所有这些都映射到单个控制器和动作,则可以这样完成:

  routes.MapRoute("Default",
                "{id}/{foo}/{bar}/{user}",
                new { controller = "Home", action = "Index", 
                      foo = String.Empty, 
                      bar = String.Empty, 
                      user = String.Empty }); 

And your Index action would look like: 并且您的Index操作看起来像:

public ActionResult Index(string id, string foo, string bar, string user) {}

If your intent is that each of those is a separate action, then consider that routes are matched in the order that they are added to the routing table. 如果您的意图是每个操作都是单独的操作,请考虑按照将它们添加到路由表的顺序进行匹配。 Therefore, always add the routes in order of most specific to broadest, and you'll be fine. 因此,始终按从最宽到最宽的顺序添加路线,这样就可以了。 So: 所以:

  routes.MapRoute("Default",
                "{id}/{foo}/{bar}/{user}",
                new { controller = "Home", action = "FooBarUser" }); 

  routes.MapRoute("Default",
                "{id}/{foo}/{bar}/",
                new { controller = "Home", action = "FooBar" }); 

  routes.MapRoute("Default",
                "{id}/{foo}/",
                new { controller = "Home", action = "Foo" }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM