You are seeing this because of the route Home/{year}
above your default route that has a default value for the {year}
parameter.
The route engine makes the following decisions:
- Start at top of route list
- Look for something that matches what your route values (controller = "Home", Action="Index").
- At the first match, return and that is your URL.
Since you have a matching controller (Home) and action (Index) as well as a default value for the year parameter, the route engine is matching to the route Home/{year}
, thus giving the url http://domain.com/Home
.
The quick fix would be either a) make year not have a default value (Home/2013
), b) move whatever that is over to a different controller (NewName/{year}
), c) move that to a different action (NewIndex/{year}
) or d) update your default route to use the year parameter instead of id
routes.MapRoute(
"Default",
"{controller}/{year}/{action}",
new {controller = "Home", action = "Index", year = 2013});
EDIT
I am not really sure what you have as far as the tryParse stuff in your route definitions, but in my testing, this seemed to accomplish what you are wanting to do:
routes.MapRoute(
name: "Test",
url: "Home/{year}",
defaults: new { controller = "Home", action = "Index"},
//this line causes the year to be an integer
constraints: new { year = @"\d+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Behaviors:
http://domain.com/ -> calls Home controller, Index action with a null value for the year parameter (no redirect to Home/2013)
http://domain.com/Home/2010 -> calls Home Controller, Index action with 2010 for the year parameter
http://domain.com/Home/ -> call Home Controller, Index action with null value for the year.
If you define a default year in the first of the two routes, then going to http://domain.com/Home will call Home controller, Index action with 2013 for the year and the redirect will still not occur.
Lastly, I suspect your Home/Index action looks something like this:
public ActionResult Index(int year){...}
If when you hit the Home/Index action, you want to automatically have the 2013 populated, then change your int to a nullable parameter and do it there rather than your routes.
public ActionResult Index(int? year){
if(!year.hasValue){
year = 2013;
}
By performing this logic here instead of the route, you should prevent the redirect to Home/ as you have no matching {year}
parameter.