views:

136

answers:

2

Hi Geeks,

I recently want to have a special routing rule : {*whatever}/details/{Id}/{itemName}

I know an exception will be thrown once I run the application. In my application, for example my url pattern is www.domain.com/root/parent/child/.../child/details/30/itemname

but the current routing doesnot support this. How can custom the routing handler to make it work?

A: 

The problem is... how will it know when to stop?

the {*whatever} segment will match:

/foo/
/foo/bar
/foo/bar/details/4/moreFoo
/foo/bar/andmore/details/4/moreFoo

Because the catch-all parameter includes anything, it will never stop.

The only way to implement this would be to create a different route for each place you use details...

eg:

games/details/{id}/{itemName}
widgets/details/{id}/{itemName}
books/details/{id}/{itemName}

Of course, that is already provided in the default {controller}/{action}/{id} route

Atømix
It can. GetRouteData parses the route from the beginning. When it comes to a greedy catch-all parameter it reverses parsing and parses from the back. When it comes back to the greedy catch-all parameter it pust all remaining content into it. I don't see a problem here. This way catch all can be anywhere in the URL as long as **there's at most one greedy catch-all parameter**.
Robert Koritnik
Interesting, I didn't know about this. Has it been this way since .Net Routing was first introduced?
Atømix
+1  A: 

I think you may want to look at extending the System.Web.Routing.RouteBase class and override the GetRouteData() method. With it you can look at the requested url and decide if matches your pattern and if so construct and return a new instance of RouteData that points to the controller and action that you want to handle the request. Otherwise if you don't match the requested url you return null.

See the following for examples:

Pro ASP.NET MVC Framework By Steve Sanderson

Custom RouteBase

Mike Glenn