C# 使用波浪号(~)符号从 URL 获取完整 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9092523/
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 05:52:39  来源:igfitidea点击:

Getting full URL from URL with tilde(~) sign

c#asp.net

提问by Daarwin

I am trying to get a typical asp.net url starting with the tilde sign ('~') to parse into a full exact url starting with "http:"

我正在尝试获取以波浪号 ('~') 开头的典型 asp.net url 以解析为以“http:”开头的完整准确 url

I have this string "~/PageB.aspx"

我有这个字符串“~/PageB.aspx”

And i want to make it become "http://myServer.com/PageB.aspx"

我想让它变成“ http://myServer.com/PageB.aspx

I know there is several methods to parse urls and get different paths of server and application and such. I have tried several but not gotten the result i want.

我知道有几种方法可以解析 url 并获取服务器和应用程序的不同路径等。我已经尝试了几个,但没有得到我想要的结果。

采纳答案by A. Tapper

If you're in a page handler you could always use the ResolveUrlmethod to convert the relative path to a server specific path. But if you want the "http://www.yourserver.se" part aswell, you'll have to prepend the Request.Url.Schemeand Request.Url.Authorityto it.

如果您在页面处理程序中,您可以始终使用该ResolveUrl方法将相对路径转换为特定于服务器的路径。但是,如果您还想要“http://www.yourserver.se”部分,则必须在其前面加上Request.Url.Schemeand Request.Url.Authority

回答by Pranay Rana

Try out

试用

System.Web.VirtualPathUtility.ToAbsolute("yourRelativePath"); 

There are various ways that are available in ASP.NET that we can use to resolve relative paths to a resource on the server-side and making it available on the client-side. I know of 4 ways -

在 ASP.NET 中有多种可用的方法,我们可以使用它们来解析服务器端资源的相对路径并使其在客户端可用。我知道 4 种方式 -

 1) Request.ApplicationPath
 2) System.Web.VirtualPathUtility
 3) Page.ResolveUrl
 4) Page.ResolveClientUrl

Good article : Different approaches for resolving URLs in ASP.NET

好文章:在 ASP.NET 中解析 URL 的不同方法

回答by user3035005

string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));

回答by user3365132

This method looks the nicest to me. No string manipulation, it can tolerate both relative or absolute URLs as input, and it uses the exact same scheme, authority, port, and root path as whatever the current request is using:

这种方法对我来说看起来最好。没有字符串操作,它可以接受相对或绝对 URL 作为输入,并且它使用与当前请求使用的任何内容完全相同的方案、权限、端口和根路径:

private Uri GetAbsoluteUri(string redirectUrl)
{
    var redirectUri = new Uri(redirectUrl, UriKind.RelativeOrAbsolute);

    if (!redirectUri.IsAbsoluteUri)
    {
        redirectUri = new Uri(new Uri(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath), redirectUri);
    }

    return redirectUri;
}