Currently I have a controller which looks something like this:
public class MyController : Controller
{
public ActionResult Action1 (int id1, int id2)
{
}
public ActionResult Action2 (int id3, int id4)
{
}
}
As you can see both my controllers have the same parameter “pattern”, two non-nullable signed integers.
My route config looks like this:
routes.MapRoute(
name: "Action2",
url: "My/Action2/{id3}-{id4}",
defaults: new { controller = "My", action = "Action2", id3 = 0, id4 = 0 }
);
routes.MapRoute(
name: "Action1",
url: "My/Action1/{id1}-{id2}",
defaults: new { controller = "My", action = "Action1", id1 = 0, id2 = 0 }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
However, I have a lot more controller actions than just these two, so basically I’ve been mapping a separate route for each one, which strikes me as pretty messy.
What I’m wondering is whether I can do something like the default route with two parameters instead of one, such as:
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id1}-{id2}",
defaults: new { controller = "Home", action = "Index", id1 = 0, id2 = 0 }
);
However, given that my parameters are not always named id1 and id2 this won’t work ( Error is “The parameters dictionary contains a null entry for parameter”. Is there a way I can do this? (Or a completely different way which is better?)
Thanks for the help!
EDIT: Based on the answers thus far it seems my question was a little misleading. I’m wanting a route with generic parameters in particular, so not tied to a specific parameter name.
I want to be able to tell the route manager that “Hey, if you get a request with the pattern {controller}/{action}/{parameter}-{parameter}, I want you to pass those two parameters to the controller and action specified regardless of their type or name!
Well, I decided to expand on Radim’s idea and design my own custom route constraint (mentioned in this question.
Basically, instead of having many different routes, I now just have one route that matches anything with two integer parameters:
In
Application_Start()underGlobal.asaxI set the controller namespace for the constraint (which is more efficient than trying to figure it out every time):And finally the custom route constraint (I know it’s a ton of code and probably overly complex but I think it’s fairly self explanatory):
Feel free to suggest improvements if you see them!