In ASP.NET 2, how do I create a route that allows lookup of an object (eg Product) by a string id (eg ProductCode)? The route for looking up the same object by it's integer id (eg ProductId) is automatic, so I don't actually know how it works.
在ASP。NET 2,如何创建允许通过字符串id(如ProductCode)查找对象(如产品)的路由?通过它的整数id(如ProductId)查找同一对象的路径是自动的,所以我实际上不知道它是如何工作的。
The automatic route by id is:
id自动路由为:
/Product/1
How do I also create a 2nd route that uses a string id?
如何创建第二个使用字符串id的路由?
/Product/red-widget
And how do I do it so that both routes are available?
我要怎么做才能让两条线路都畅通?
1 个解决方案
#1
19
You should take a look at using a route constraint to do this. See http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs
您应该了解如何使用路由约束来实现这一点。参见http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="DetailsByName"},
new {productId = @"\w+" }
);
In the above, the constraint regex "\w+" should limit to routes that match only "word" characters (take a look at regex docs for more details on patterns used here).
在上面,约束regex“\w+”应该限制为只匹配“word”字符的路由(有关这里使用的模式的更多细节,请参阅regex文档)。
#1
19
You should take a look at using a route constraint to do this. See http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs
您应该了解如何使用路由约束来实现这一点。参见http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="DetailsByName"},
new {productId = @"\w+" }
);
In the above, the constraint regex "\w+" should limit to routes that match only "word" characters (take a look at regex docs for more details on patterns used here).
在上面,约束regex“\w+”应该限制为只匹配“word”字符的路由(有关这里使用的模式的更多细节,请参阅regex文档)。