【问题标题】:Is there an equivalent to GetRouteUrl() at application/class level (.Net 4.8)?在应用程序/类级别(.Net 4.8)是否有等效于 GetRouteUrl() 的方法?
【发布时间】:2019-09-24 10:48:26
【问题描述】:

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

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

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

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

MSDN documentation 声明:

提供此方法是为了编码方便。它相当于 打电话给RouteCollection.GetVirtualPath(RequestContext, RouteValueDictionary) method。此方法将对象转换为 通过使用将 routeParameters 传递给 RouteValueDictionary 对象 RouteValueDictionary.RouteValueDictionary(Object) 构造函数。

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

【问题讨论】:

    标签: asp.net webforms webforms-routing


    【解决方案1】:

    以下工作可在应用程序/类级别生成 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;
    

    【讨论】:

      【解决方案2】:

      我的 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 页面选取任何“不存在”的页面。

      希望这对您有所帮助或至少能给您提供更多想法。

      【讨论】:

      • 抱歉,我认为我没有正确解释自己。我只是想在页面之外生成一个 URL。如果需要一个页面,那么这将不起作用,因为我在应用程序级别而不是页面级别进行操作。
      猜你喜欢
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多