asp.net - 在应用程序/类级别(.Net 4.8)是否有等效于 GetRouteUrl() 的方法?
问题描述
在经典的 webforms ASPX 页面中,我使用以下内容创建 URL 路由:
var url = this.GetRouteUrl("MyRouteName", new {UserId = 123}); // Generates /UserId/123
MyRouteName
Routes.RegisterRoutes()
在启动时使用的方法中定义。
但是,我需要在应用程序级别的辅助方法中生成一个 URL。那里显然没有页面上下文,所以我得到一个错误。
MSDN 文档指出:
提供此方法是为了编码方便。相当于调用RouteCollection.GetVirtualPath(RequestContext, RouteValueDictionary) 方法。此方法使用RouteValueDictionary.RouteValueDictionary(Object)构造函数将在 routeParameters 中传递的对象转换为RouteValueDictionary对象。
我阅读了这些,但无法弄清楚我需要实现的目标是否可行。在线搜索发现了一些答案,但这些答案已有多年历史,不易实施。
解决方案
以下工作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;
推荐阅读
- python - 从列和水平线创建矩阵
- python - 数组在python中不可调用“'numpy.ndarray'对象不可调用”
- python - (python 中的 TCP 客户端编程)如何在使用 recv() 获取正则表达式中正确地生成我的十六进制字符串?
- r - 在ggplot中的每个栏下添加标签
- java - Java 无法将 reactor.core.publisher.MonoDefer 转换为 EntityClass
- css - 如何根据媒体查询有效地使用不同的字体权重
- nodes - npm 错误 npm 错误!代码 ETARGET npm 错误!notarget 没有为 express@undefined4.16.3 找到匹配的版本
- spring - Spring Boot Admin客户端问题
- doctrine-orm - 生产环境中的查询过多
- javascript - Firebase Firestore 未在 google chrome 中获取数据