0

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.

EvilDr
  • 8,943
  • 14
  • 73
  • 133

2 Answers2

0

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;
EvilDr
  • 8,943
  • 14
  • 73
  • 133
-1

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.

KH S
  • 444
  • 1
  • 4
  • 8
  • Sorry I don't think I've explained myself properly. I'm just trying to generate a URL outside a page. If a page is required then this won't work because I'm operating at application level and not page level. – EvilDr Sep 24 '19 at 11:48