I found something strange with routing…
I´m testing a MVC3 application in Visual Studio Web Express 2012
- I created a new MVC3 application to isolate the problem
-
I added the following route before the default route:
routes.MapRoute( "default_localization", "{language}/{country}/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); -
Then without any other change (there are no areas anything just the initial files after creating the project), I ran the application and at first sight everything was working fine. Since it is a new application there are two links at the top of the page:
- Home
- About
The action links look like:
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
Then this is what is happening:
-
When the browser URL is:
http://localhost:54870/- The Home link is:
http://localhost:54870/ - The About link is:
http://localhost:54870/Home/About
HTML
<li><a href="/">Home</a></li> <li><a href="/Home/About">About</a></li>Which is OK
- The Home link is:
-
But after clicking the About link, the browser URL is:
http://localhost:54870/Home/About- The Home link becomes:
http://localhost:54870/Home/About - The about link becomes:
http://localhost:54870/Home/About/Home/About
They still execute the correct action even when the link is messed up.
HTML
<li><a href="/Home/About">Home</a></li> <li><a href="/Home/About/Home/About">About</a></li> - The Home link becomes:
If I remove my custom routing everything works as expected
-
Why is this happening?
-
How can I fix it?
I just found the problem
Basically I read several routing articles and finally I got it, my problem was that my custom route was been picked up always after I clicked the About link
Why?
Let’s consider it:
When my URL was
http://localhost:54870/, my custom route was not picked up because I didn’t have default values for {language} and {country} therefore my route didn’t matchBut when my URL was
http://localhost:54870/Home/Aboutmy custom route was always picked up because the route engine assumed that Home/About were the {language} and {country} segments and since I had default values for {controller} and {action} the rout simply was a matchWell I learnt my lesson and I learnt more about routing. In the future I’m planning to follow the KISS principle when defining routes