回答这个问题可能有点晚了,但我发现自己处于同样的情况(即我需要生成一个 URL 而没有相应的 IHttpRoute 名称)。但是,您可以仅使用 Route 和 HttpRequestMessage 生成 URL。
var parameters = new Dictionary{{"id" , 123}, {HttpRoute.HttpRouteKey, true}};
var path = Route.GetVirtualPath(request, parameters);
var uri = path.VirtualPath;
重要的部分是将 HttpRoute.HttpRouteKey 添加到参数中,如果未使用此值,则 GetVirtualPath 返回 null。请参阅HttpRoute.cs中的代码
// Only perform URL generation if the "httproute" key was specified. This allows these
// routes to be ignored when a regular MVC app tries to generate URLs. Without this special
// key an HTTP route used for Web API would normally take over almost all the routes in a
// typical app.
if (values != null && !values.Keys.Contains(HttpRouteKey, StringComparer.OrdinalIgnoreCase))
{
return null;
}