[英]Routes in ASP.NET MVC 5
My requirement is I need to set multiple routes to same controller/action method.我的要求是我需要将多个路由设置为相同的控制器/操作方法。
If user enters url http://localhost:xxxx/home/index , it will target "index" action method of "home" controller.如果用户输入 url http://localhost:xxxx/home/index ,它将针对“home”控制器的“index”操作方法。
I also want " http://localhost:xxxx/products " and " http://localhost:xxxx/categories " to point to "index" action method of "home" controller.我还希望“ http://localhost:xxxx/products ”和“ http://localhost:xxxx/categories ”指向“home”控制器的“index”操作方法。
I was able to achive this by adding two routes "categories" and "products" as mentioned below , and it is working fine.我能够通过添加下面提到的两条路线“类别”和“产品”来实现这一点,并且工作正常。
routes.MapRoute(
name: "categories",
url: "categories",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "products",
url: "products",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
My question is , is there any way I combine those two routes "categories" and "products" in to one ?我的问题是,有什么办法可以将这两条路线“类别”和“产品”合二为一?
You can achieve this by adding a constraint to your route.您可以通过向路线添加约束来实现这一点。
Make the entire path a parameter, and then assign a regular expression rule to match this parameter.将整个路径作为一个参数,然后分配一个正则表达式规则来匹配这个参数。
routes.MapRoute(
name: "IndexMapper",
url: "{alternateIndexName}",
defaults: new { controller="Home", action="Index" },
constraints: new { alternateIndexName="(categories)|(products)"}
);
https://msdn.microsoft.com/en-us/library/cc668201.aspx#Anchor_6 https://msdn.microsoft.com/en-us/library/cc668201.aspx#Anchor_6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.