Within classic webforms ASPX pages, I create URL routes using the following:
var url = this.GetRouteUrl("MyRouteName", new {UserId = 123}); // Generates /UserId/123
MyRouteName
is defined within the Routes.RegisterRoutes()
method used at startup.
However, I need to generate a URL within a helper method that lives at application-level. There is obviously no page context there, so I get an error.
The MSDN documentation states:
This method is provided for coding convenience. It is equivalent to calling the RouteCollection.GetVirtualPath(RequestContext, RouteValueDictionary) method. This method converts the object that is passed in routeParameters to a RouteValueDictionary object by using the RouteValueDictionary.RouteValueDictionary(Object) constructor.
I read these, but cannot figure out whether what I need to achieve is possible. An online search revealed some answers, but these are many years old an not easy to implement.
The following works to generate the equivalent of GetRouteUrl
at application/class level:
var url = RouteTable.Routes.GetVirtualPath(null,
"MyRouteName",
new RouteValueDictionary(new { UserId = 123 })).VirtualPath;
Remember that only returns a local Url (e.g. /UserId/123) so if you need to domain name you'll have to prepend that as well:
var url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + RouteTable.Routes.GetVirtualPath(null,
"MyRouteName",
new RouteValueDictionary(new { UserId = 123 })).VirtualPath;