How do you convert a url to a virtual path in asp.net without manual string parsing?

烈酒焚心 提交于 2020-01-22 20:09:20

问题


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.


回答1:


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);



回答2:


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".



来源:https://stackoverflow.com/questions/493580/how-do-you-convert-a-url-to-a-virtual-path-in-asp-net-without-manual-string-pars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!