I am just getting introduced to ASP.NET routing and have two routes registered at the moment:
routes.MapPageRoute(
"default",
"{Path}/{Name}.aspx{Query}",
"~/Default.aspx",
true,
new RouteValueDictionary { { "Name", "default" } },
new RouteValueDictionary { { "Name", @"[-_\w]+" } });
routes.MapPageRoute(
"home",
"{Name}.aspx{Query}",
"~/Default.aspx",
true,
new RouteValueDictionary { { "Name", "default" } },
new RouteValueDictionary { { "Name", @"[-_\w]+" } });
However, when I try to build urls using these routes, I always get an exception. I tried this:
private string GetVirtualPath(RouteValueDictionary values)
{
return RouteTable.Routes.GetVirtualPath(
null, values).VirtualPath;
}
and also this:
private string GetVirtualPath(RouteValueDictionary values)
{
var wrapper = new HttpContextWrapper(HttpContext.Current);
return RouteTable.Routes.GetVirtualPath(
new RequestContext(wrapper,
RouteTable.Routes.GetRouteData(wrapper)),
values).VirtualPath;
}
Either way, I get a null reference exception on RouteTable.Routes.GetVirtualPath
when I call:
GetVirtualPath(new RouteValueDictionary { { "Name", entity.Name } });
Or even:
GetVirtualPath(new RouteValueDictionary { { "Name", entity.Name }, { "Query", string.Empty } });
What could I be doing wrong here?
I guess I'll answer my own question. The problem was with my route restrictions. Once I removed the lines with new RouteValueDictionary { { "Name", @"[-_\w]+" } }
everything started working.