你怎么一个URL转换为虚拟路径在asp.net中无需人工字符串解析? [英] How do you convert a url to a virtual path in asp.net without manual string parsing?
问题描述
我已经看到了关于从虚拟到绝对和URL转换类似的问题和答案,但我怎么能一个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?
例如:
我要的http://myserver/home.aspx转换为:〜/ home.aspx
I want "http://myserver/home.aspx" converted to: "~/home.aspx"
我认识上面的例子是一个简单的字符串分析例程,但是我正在寻找一个合适的解决方案,将扩展到URL格式的变化。
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.
推荐答案
您可以得到其中大部分来自Uri类:
You can get most of it from the Uri class:
new Uri("http://myserver.com/home.aspx").AbsolutePath
然后你只需要prePEND了〜
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.
编辑:这可能做到这一点:
This might do it:
VirtualPathUtility.ToAppRelative(new Uri("http://myserver.com/home.aspx").AbsolutePath);
这篇关于你怎么一个URL转换为虚拟路径在asp.net中无需人工字符串解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!