I am trying to set up my MVC application with the root as follows:
- mysite.com/ -> Index action
- mysite.com/thingID -> to CurrentThing action
- mysite.com/thingID/year -> to CurrentThing action
Action: public ActionResult CurrentThing(string thingID, int year)
I also need the regular controller/action route to work both with and without an id. ThingID is a string. I have the following routes defined:
routes.MapRoute(
"Regular",
"{controller}/{action}/{id}",
new { id = UrlParameter.Optional }
);
routes.MapRoute(
"RootSpecificRecord",
"{thingID}/{year}",
new { controller = "Things", action = "CurrentThing", year = DateTime.Now.Year }
);
routes.MapRoute(
"Root",
"",
new { controller = "Things", action = "Index" }
);
This works fine until I go to mysite.com/id/year at which point the first route treats the id as a controller and the year as an action. How can I resolve this?
The routing engine is unable to tell the difference between
/{controller}/{action}/{id}and/{ThingId}/{year}Since your id parameter is optional, and you don’t have any constraints that ThingId is an id.
You could try putting the RootSpecificRecord route first, and altering the Id so that it will only accept an integer. This will make it so it’s more specific than your regular route. Assuming ofcourse that thingID is an integer, you could alter your route like this:
See this blog post about route constraints, if you want to create a different constraint.