Sorry for asking a rather n00b question, I am rather new to ASP.NET MVC.
My problem is as follows:
I want my site to handle a URL in the following way:
www.mysite.com/homepage/name
I want the above link to go to that user’s profile. For simplicity the controller will be the Homepage controller with the Test action.
Meaning that the global.asax routing will be:
routes.MapRoute(
"test",
"homepage/{name}",
new { controller = "Homepage", action = "Test" }
);
Up until now the code works great (I have tested it and it routes ok).
But now my other functionality which I want is to enable:
www.mysite.com/homepage/action/id
To work as well.
The routing for this will be:
routes.MapRoute(
"Default",
"homepage/{action}/{id}",
new { controller = "Homepage", action = "Index", id = UrlParameter.Optional }
);
The problem is what happens when a user wants to omit the {id} for an action, the routing table detects that the action name is actually the {name} parameter.
Is there any way to first CHECK if an action exists. And only if it doesn’t, then use it as a parameter for a different route.
Makes sense? if not I’ll add some more details.
Thanks!
EDIT
So I’ve managed to solve this using the constraints regex
I placed a regex defining a all the actions in my controller:
routes.MapRoute(
"homepage",
"homepage/{action}/{id}",
new { controller = "Homepage", action = "Index", id = UrlParameter.Optional },
new { action = "(action1|action2|action3)" }
);
And then the next rule:
routes.MapRoute(
"feed",
"homepage/{id}",
new { controller = "Homepage", action = "Test"}
);
I works ok, only it’s hard to scale upon this. You need to remember to place every new action on the controller inside the string here. It’s a huge opening for debug nightmares.
Thank you !
You need to put the
Defaultroute first, and also restrict its allowed valuesThis way the first route will only be used if the action value matches one provided in the constraint, otherwise it will move to the next rule.
You will also have to make sure when you create user profiles, that no name should match one of your supported actions for the
defaultroute.