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.
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace InfosoftConnectSandbox
{
public class RouteConfig
{
class TestRoute : RouteBase
{
Regex re = new Regex(@"folder/city-(?<pid>\d)-(?<id>\d)-.*");
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var data = new RouteData();
var url = httpContext.Request.Url.ToString();
if (!re.IsMatch(url))
{
return null;
}
foreach (Match m in re.Matches(url))
{
data.Values["pid"] = m.Groups["pid"].Value;
data.Values["id"] = m.Groups["id"].Value;
}
data.RouteHandler = new PageRouteHandler("~/mypage.aspx");
return data;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return new VirtualPathData(this, "~/mypage.aspx");
}
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new TestRoute());
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}