One of major hurdles I seem to be having recently is getting my head around some of the more complex routing requirements for some MVC based applications I\'ve been developing.
I don't understand, why can't you just define each one of them as a separate route, using regular expression when needed. For example to differentiate between the /blog/year/month/day/title
and /blog/title
.
Each one of those sets is a separate case, and you'll need to tell MVC what to do with each one. You can do this by defining the rule once
in the Global.asax.cs
file:
For the first case: /blog/year/month/day/title
routes.MapRoute(
"Blog Full Route", // Route name
"blog/{year}/{month}/{day}/{title}", // URL with parameters
new {controller = "blog", action = "post"}, // Defaults
new {year = @"\d+", month= @"\d+", day = @"\d+"} // Constrain parameters with RegEx patterns
);
For second case: /blog/title
routes.MapRoute(
"Blog Title Route", // Route name
"blog/{title}", // URL with parameters
new {controller = "blog", action = "post"}, // Defaults
);
For last case: /title
routes.MapRoute(
"Title Route", // Route name
"{title}", // URL with parameters
new {controller = "blog", action = "post"}, // Defaults
);
The trick is putting theses routes in this exact order, with the least specific at the bottom. Changing the order would result in the wrong route being used (specifically in the last two). If the last case was switched with the second case, URLS of the type blog/SomeTitle
would route to the post
action with blog
as the title.
Whenever you're creating a route for something, keep the following in mind:
very
aware of route order (which route comes before which){something}
denote action parameters Some good tutorials: