【发布时间】:2018-07-18 11:44:41
【问题描述】:
Goooooogling 大约 15 分钟后,我找不到这个简单问题的解决方案。有什么小帮助吗?
应用程序托管在网站的 web 子文件夹中,我需要映射一个相对 Uri(这是 RouteController 中的 Hello 操作,它以 int 和 string 作为参数):
"~/Route/Hello/129?name=kennyzx"
到
http://myserver/web/myapplication/Route/Hello/129?name=kennyzx
如果我使用
HttpContext.Current.Server.MapPath("~/Route/Hello/129?name=kennyzx");
它抛出异常,因为问号? 是非法字符。
所以我需要先将Uri分成~/Route/Hello/129和?name=kennyzx两部分,然后MapPath取第一部分,Path.Combine连接MapPath的结果和查询字符串。
有没有更简单的方法来做到这一点?
我意识到我使用了错误的 API,它实际上扩展到了我服务器上的真实文件路径!
这就是我想要做的:
我有一堆相对 uris,我想在 Razor 页面中编写一个函数将它们扩展为绝对 uris。
@{
ViewBag.Title = "Route Testing";
var link1 = "/Route/Hello/129?name=kennyzx";
var link2 = "~/Route/Hello/129?name=kennyzx";
}
@functions{
private static string GetAbsoluteUri(string link)
{
string absoluteUri = HttpContext.Current.Server.MapPath(link);
return absoluteUri;
}
}
<h2>Route Testing</h2>
<a href="@link1">@link1</a><br />
<a href="@link2">@link2</a><br />
<a href="@GetAbsoluteUri(@link2)">@link2</a><br />
但以上都没有得到正确的绝对路径。
第一个扩展为http://myserver/Route/Hello/129?name=kennyzx,
第二个扩展为http://myserver/web/myapplication/~/Route/Hello/129?name=kennyzx
第三个抛出异常,这就是我问这个问题的原因。
【问题讨论】:
-
为什么要将查询字符串附加到文件夹名称上?没意义
-
这不是文件夹名称,它是 RouteController 中的 Hello Action,它接受一个 int (id) 和一个字符串作为参数。
-
好的,
Server.MapPath()返回一个文件夹。我认为您需要重新考虑您的问题并澄清您想要做什么。例如,Server.MapPath("~/index.html")可能返回c:\inetpub\wwwroot\index.html -
@Archer 谢谢。我已经编辑了我的问题。现在我明白这不是正确的 API。基本上我只想从 Razor 页面访问该链接,困难在于应用程序没有部署到网站的根目录,而是部署在虚拟目录中。
标签: c# asp.net-mvc uri server.mappath