I have a webforms-project where I use System.Web.Routing.RouteCollection.MapPageRoute to rewrite URLs but I have a problem with a few dynamic URLs. My URL could look like this;
/folder/city-1-2-something.aspx
and the MapPageRoute for this looks like this
routeCollection.MapPageRoute("CompanyCity", "folder/city-{id}-{pid}-{title}.aspx", "~/mypage.aspx");
But I have realized that some URLs could look like this
/folder/city-2-2-something-something.aspx
/folder/city-2-2-something-something-something.aspx
/folder/city-2-2-something-something-something-something.aspx
and these are not cought correctly by my routing - the first example will end up with the results id = 2-2 and pid = something instead of id = 2 and pid = 2.
The {title} is not important - only {id} and {pid} are used. I have several similar routes to specific folders, so as far as I can se I cannot use a catch all. But how can I fix this issue?
The simple RouteConfig below contains a TestRoute that matches exactly what you need. And nothing more,so it is in a sense quite bad code.
But the idea is that it is now possible to use regular expressions which can quite easily match your needs. (The named groups "id"
(?<id>\d)
and "pid"(?<pid>\d)
only matches digits (\d
) why they will only match until next dash.)Hope it can be of some inspiration.