如何在 ASP.NET 中将 url 转换为虚拟路径而不需要手动字符串解析?
我见过关于从虚拟到绝对和 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从 Uri 类中获取大部分内容:
然后您只需在前面加上 ~
不过,如果您托管在子目录中,这可能会中断 - 我认为没有办法在应用程序的上下文中专门执行此操作你正在跑步。
编辑:这可能会做到这一点:
You can get most of it from the Uri class:
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 方法(字符串)似乎就是您正在寻找的(http: //msdn.microsoft.com/en-us/library/ms150163.aspx)
VirtualPathUtility.ToAppRelative Method (String) seems to be what you are looking for (http://msdn.microsoft.com/en-us/library/ms150163.aspx)