首页 > 解决方案 > 在应用程序/类级别(.Net 4.8)是否有等效于 GetRouteUrl() 的方法?

问题描述

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

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

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

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

MSDN 文档指出:

提供此方法是为了编码方便。相当于调用RouteCollection.GetVirtualPath(RequestContext, RouteValueDictionary) 方法。此方法使用RouteValueDictionary.RouteValueDictionary(Object)构造函数将在 routeParameters 中传递的对象转换为RouteValueDictionary对象。

我阅读了这些,但无法弄清楚我需要实现的目标是否可行。在线搜索发现了一些答案,但这些答案已有多年历史,不易实施。

标签: asp.netwebformswebforms-routing

解决方案


以下工作GetRouteUrl在应用程序/类级别生成等效项:

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

请记住,它只返回一个本地 URL(例如 /UserId/123),因此如果您需要域名,您还必须在前面加上:

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

推荐阅读