在 application/class 级别(.Net 4.8)是否有等效于 GetRouteUrl() 的东西?

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

在经典的 webforms ASPX 页面中,我使用以下方法创建 URL 路由:

var url = this.GetRouteUrl("MyRouteName", new {UserId = 123}); // Generates /UserId/123

MyRouteName 在启动时使用的 Routes.RegisterRoutes() 方法中定义。

但是,我需要在应用程序级别的辅助方法中生成 URL。那里显然没有页面上下文,所以我得到一个错误。

MSDN documentation 状态:

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.

我读了这些,但无法弄清楚我需要实现的目标是否可行。网上搜索了一些答案,但这些都已经很多年了,不容易实现。

我的 Global.asax 文件在 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");

然后我的 Routing.aspx.cs 页面处理请求发生的逻辑。 主要是我 Server.Transfer 到一个将显示请求页面的 aspx 页面。

Routing.aspx 页面选取任何 "non-existing" 页面。

希望这对您有所帮助,或者至少能给您一些更多的想法。

以下工作可在 application/class 级别生成 GetRouteUrl 的等价物:

var url = RouteTable.Routes.GetVirtualPath(null, 
                                           "MyRouteName", 
                                           new RouteValueDictionary(new { UserId = 123 })).VirtualPath;

请记住,只有 returns 本地 Url(例如 /UserId/123),因此如果您需要域名,您也必须在前面加上:

var url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + RouteTable.Routes.GetVirtualPath(null, 
                                                                                      "MyRouteName", 
                                                                                      new RouteValueDictionary(new { UserId = 123 })).VirtualPath;