ASP.NET MVC routing by string id?

2020-07-02 12:00发布

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.

The automatic route by id is:

/Product/1

How do I also create a 2nd route that uses a string id?

/Product/red-widget

And how do I do it so that both routes are available?

1条回答
再贱就再见
2楼-- · 2020-07-02 12:34

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

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).

查看更多
登录 后发表回答