如何在 ASP.NET 中将 url 转换为虚拟路径而不需要手动字符串解析?

发布于 2024-07-13 08:22:03 字数 268 浏览 7 评论 0原文

我见过关于从虚拟到绝对和 url 的转换的类似问题和答案,但是如何在不手动字符串解析的情况下将 url 转换为虚拟路径?

示例:

我希望将“http://myserver/home.aspx”转换为:“~/home.aspx “

我意识到上面的例子是一个简单的字符串解析例程,但我正在寻找一个适当的解决方案,可以适应 url 格式的变化。

I've seen similar questions and answers regarding conversions from virtual to absolute and url, but how can I convert a url to a virtual path without manual string parsing?

Example:

I want "http://myserver/home.aspx" converted to: "~/home.aspx"

I realize the above example would be an easy string parsing routine, but I'm looking for a proper solution that will scale to the changing of the url format.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

意中人 2024-07-20 08:22:03

您可以从 Uri 类中获取大部分内容:

new Uri("http://myserver.com/home.aspx").AbsolutePath

然后您只需在前面加上 ~

不过,如果您托管在子目录中,这可能会中断 - 我认为没有办法在应用程序的上下文中专门执行此操作你正在跑步。

编辑:这可能会做到这一点:

VirtualPathUtility.ToAppRelative(new Uri("http://myserver.com/home.aspx").AbsolutePath);

You can get most of it from the Uri class:

new Uri("http://myserver.com/home.aspx").AbsolutePath

Then you just have to prepend the ~

Though, that will might break if you host in a subdirectory - I don't think there's a way to do it specifically in the context of the application you're running.

EDIT: This might do it:

VirtualPathUtility.ToAppRelative(new Uri("http://myserver.com/home.aspx").AbsolutePath);
夏末染殇 2024-07-20 08:22:03

VirtualPathUtility.ToAppRelative 方法(字符串)似乎就是您正在寻找的(http: //msdn.microsoft.com/en-us/library/ms150163.aspx)

如果应用程序的虚拟路径是“myapp”,并且虚拟路径“/myApp/sub/default.asp”被传递到 ToAppRelative 方法中,则生成的应用程序相对路径是“~/sub/default.aspx” ”。

VirtualPathUtility.ToAppRelative Method (String) seems to be what you are looking for (http://msdn.microsoft.com/en-us/library/ms150163.aspx)

If the virtual path for the application is "myapp" and the virtual path "/myApp/sub/default.asp" is passed into the ToAppRelative method, the resulting application-relative path is "~/sub/default.aspx".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文