C# 从 Request.Url.AbsolutePath 获取应用相对 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9701309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:28:05  来源:igfitidea点击:

Get app relative url from Request.Url.AbsolutePath

c#asp.net

提问by jgauffin

How can I get the application relative url from Request.Url.AbsolutePath?

如何从中获取应用程序的相对 url Request.Url.AbsolutePath

VirtualPathUtilityseems to only work with ~/XXXurls?

VirtualPathUtility似乎只适用于~/XXX网址?

采纳答案by jgauffin

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

回答by Pankaj

 String appUrl = VirtualPathUtility.ToAbsolute("~/");
 String RelativePath = new System.Uri(Page.Request.Url, "").PathAndQuery.Substring(appUrl.Length-1)

回答by Ashwin Singh

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

例如,如果 URL 是www.example.com/products?A=a&B=b&C=c,则上面的代码将返回/products?A=a&B=b&C=c

回答by John Gibb

I think this is the cleanest way:

我认为这是最干净的方式:

new Uri(Request.Url.PathAndQuery, UriKind.Relative))

回答by Stjepan Rajko

This worked for me:

这对我有用:

VirtualPathUtility.MakeRelative("~", Request.Url.AbsolutePath)

For example if the root of the website is /Websiteand Request.Url.AbsolutePathis /Website/some/paththis will return some/path.

例如,如果网站的根是/WebsiteRequest.Url.AbsolutePath/Website/some/path这将返回some/path.

回答by ccook

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

回答by Ian Grainger

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#jazzbecomes /abc/d?foo=bar#jazz.

于是http://localhost:8080/abc/d?foo=bar#jazz变成/abc/d?foo=bar#jazz