I’m trying to implement routing such as the following:
posts/535434/This-is-a-post-title
posts/tagged/tags+here // Matches {controller}/{action}/{id} - Default // Displays all posts with the specified tags // uses PostsController : ActionTagged(string tags) posts?pageSize=50&pageIndex=4 // Matches {controller}/{action}/{id} - Default // Displays all posts // uses PostsController : Index(int? pageSize, int? pageIndex)
Here’s the problem I want to do this:
posts/39423/this-is-a-post-title-here // Typically this is implemented using an action like 'Details' // and would normally look like : posts/details/5
I can’t seem to get the routing working right. I tried something like this:
{controller}/{id}/{description}
and set the default action to be ‘Display’ which works, but then won’t allow me to navigate to other named actions like ‘Tagged’.
What am I missing?
Thanks!
Two things:
First, you should always order your routes in decreasing specificity (e.g. most specific case first, least specific case last) so that routes will ‘fall through’, if one doesn’t match it will try the next.
So we want to define {controller}/{postid}/… (must be a postid) before we define {controller}/{action}/… (could be anything else)
Next, we want to be able to specify that if the provided value for postid does not look like a Post ID, the route should fail and fall through to the next one. We can do this by creating an IRouteConstraint class:
We can add it to the route definition like so: