I have stumbled upon a curious behavior in ASP.NET MVC Routing.
In my RouteConfig file, when I map a route like this (the default route):
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
Using:
@Html.ActionLink("Index", "Home")
I get a nice, clean and short URL, like: http://mysite/
But if I add another optional parameter after id, like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{name}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
name = UrlParameter.Optional
}
);
The same ActionLink outputs this URL: http://mysite/home/index every time. I verified the same behavior using RedirectToAction.
My questions are: Is there a way to work around this and get the shorter URL in the later case? Why ASP.NET MVC Routing engine behaves differently in these cases?
EDIT
I managed to work around this issue following the instructions posted by Dave A. I added a custom route before the "Default" route that matches my custom URL pattern.
routes.MapRoute(
name: "Custom",
url: "{controller}/{action}/{id}/{name}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);