Is there an equivalent to GetRouteUrl() at application/class level (.Net 4.8)?

86 views Asked by At

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.

2

There are 2 answers

0
EvilDr On BEST ANSWER

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;
1
KH S On

I have in my Global.asax file in the Application_Start

RouteTable.Routes.MapPageRoute("Level1", "{lvl1}", "~/Routing.aspx");//Any name will do for the aspx page.
RouteTable.Routes.MapPageRoute("Level2", "{lvl1}/{*lvl2}", "~/Routing.aspx");

Then my Routing.aspx.cs page handles the logic for what will happen with the request. Mainly I Server.Transfer to an aspx page which will display the requested page.

Routing.aspx page picks up any "non-existing" page.

Hope this helps or at least gives you some more ideas.