[英]Get app relative url from Request.Url.AbsolutePath
How can I get the application relative url from Request.Url.AbsolutePath
? 如何从
Request.Url.AbsolutePath
获取应用程序相对URL?
VirtualPathUtility
seems to only work with ~/XXX
urls? VirtualPathUtility
似乎只适用于~/XXX
网址?
Its a little late to answer but there is a elegant solution to this. 它的回答有点晚,但有一个优雅的解决方案。 You can use
您可以使用
Request.Url.PathAndQuery
This will return the relative path of the page. 这将返回页面的相对路径。
For example, if the URL is www.example.com/products?A=a&B=b&C=c
, the above piece of code will return /products?A=a&B=b&C=c
例如,如果网址是
www.example.com/products?A=a&B=b&C=c
,则上面的代码将返回/products?A=a&B=b&C=c
I solved it like this: 我这样解决了:
// create an absolute path for the application root
var appUrl = VirtualPathUtility.ToAbsolute("~/");
// remove the app path (exclude the last slash)
var relativeUrl = HttpContext.Current.Request.Url.AbsolutePath.Remove(0, appUrl.Length - 1);
To do this without using string manipulation and handling the application's relative path I used: 要在不使用字符串操作和处理我使用的应用程序相对路径的情况下执行此操作:
var relativeUrl = VirtualPathUtility.ToAppRelative(
new Uri(context.Request.Url.PathAndQuery, UriKind.Relative).ToString());
This worked for me: 这对我有用:
VirtualPathUtility.MakeRelative("~", Request.Url.AbsolutePath)
For example if the root of the website is /Website
and Request.Url.AbsolutePath
is /Website/some/path
this will return some/path
. 例如,如果网站的根目录是
/Website
而Request.Url.AbsolutePath
是/Website/some/path
则会返回some/path
。
我认为这是最干净的方式:
new Uri(Request.Url.PathAndQuery, UriKind.Relative))
String appUrl = VirtualPathUtility.ToAbsolute("~/");
String RelativePath = new System.Uri(Page.Request.Url, "").PathAndQuery.Substring(appUrl.Length-1)
To build on Ashwin Singh's nice answer - I needed the anchor link to be included with my relative URL, so I just re-added it at the end: 在Ashwin Singh的基础上建立了很好的答案 - 我需要将锚链接包含在我的相对URL中,所以我在最后重新添加它:
Request.Url.PathAndQuery + Request.Url.Fragment
So http://localhost:8080/abc/d?foo=bar#jazz
becomes /abc/d?foo=bar#jazz
. 所以
http://localhost:8080/abc/d?foo=bar#jazz
变为/abc/d?foo=bar#jazz
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.