从 C# 中的字符串中提取基本 URl?

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

Extract base URl from a string in c#?

c#.netstring

提问by PushCode

I am currently working on a project with .NET 1.1 framework and I am stuck at this point. I have a string like "http://www.example.com/mypage/default.aspx" or it might be "http://www.example.edu/mypage/default.aspx" or "http://www.example.eu/mypage/default.aspx". How can I extract the base URl from this kind of a string.

我目前正在使用 .NET 1.1 框架开发一个项目,但我被困在了这一点上。我有一个类似“ http://www.example.com/mypage/default.aspx”的字符串,或者它可能是“ http://www.example.edu/mypage/default.aspx”或“ http://www .example.eu/mypage/default.aspx”。如何从这种字符串中提取基本 URl。

Thanks

谢谢

采纳答案by Adil

You can use URIclass to get the host name.

您可以使用URI类来获取主机名。

var uri = new Uri("http://www.example.com/mypage/default.aspx");    
var host = uri.Host;

EditYou can use uri.Schemeand uri.Portto get the .Scheme e.g. (http, ftp) and .Port to get the port number like (8080)

编辑您可以使用uri.Schemeuri.Port来获取.Schemeeg (http, ftp) 和 .Port 来获取像 (8080) 这样的端口号

string host = uri.Host;
string scheme = uri.Scheme;
int port = uri.Port;

You can use Uri.GetLeftPartto get the base URL.

您可以使用Uri.GetLeftPart来获取基本 URL。

The GetLeftPartmethod returns a string containing the leftmost portion of the URI string, ending with the portion specified by part.

GetLeftPart方法返回包含URI字符串的最左侧部分的字符串,由部分所指定的部分结束。

var uri = new Uri("http://www.example.com/mypage/default.aspx");    
var baseUri = uri.GetLeftPart(System.UriPartial.Authority);

The following examples show a URI and the results of calling GetLeftPart with Scheme, Authority, Path, or Query, MSDN. enter image description here

以下示例显示了一个 URI 以及使用 Scheme、Authority、Path 或 Query、MSDN调用 GetLeftPart 的结果。 在此处输入图片说明

回答by spender

var builder = new UriBuilder("http://www.example.com/mypage/default.aspx");
builder.Path = String.Empty;
var baseUri = builder.Uri;
var baseUrl = baseUri.ToString();
// http://www.example.com/

回答by MethodMan

If you want to get all 3 of them in a list here is something you could also start with there are so many options you can do once you get the Host Namealso if you are wanting everything past the .comuse the AbsolutePathmethod

如果你想把所有 3 个都放在一个列表中,你也可以从这里开始,一旦你得到了,你可以做很多选择,Host Name如果你想要.com使用该AbsolutePath方法之后的一切

var uriList = new List<string>()
            {
                "http://www.mysite.com/mypage/default.aspx",
                "http://www.mysite.edu/mypage/default.aspx",
                "http://www.mysite.eu/mypage/default.aspx"
            };
        var holdList = new List<string>();
        foreach (var uriName in uriList)
        {
            Uri uri = new Uri(uriName);
            holdList.Add(uri.Host);
        }

回答by Myster

Short Answer

简答

myUri.GetLeftPart(System.UriPartial.Authority)

Long Answer
Assuming "Base URI" means something like http://www.example.com, you can get the base uri like this:

长答案
假设“基本 URI”的意思是类似的http://www.example.com,你可以像这样获得基本 URI:

var myUri= new Uri("http://www.example.com/mypage/default.aspx");    
var baseUri = myUri.GetLeftPart(System.UriPartial.Authority)

This gives: http://www.example.com

这给出: http://www.example.com

Note: uri.Hostgives: www.example.com(not including port or scheme)

注意:uri.Host给出:(www.example.com不包括端口或方案)

回答by Joseph M. Rice

Just create an extension to the Uri class. In my opinion things that should be there from the start. It will make your life easier.

只需为 Uri 类创建一个扩展。在我看来,事情从一开始就应该存在。它会让你的生活更轻松。

public static class UriExtensions
 {                   
    public static Uri AttachParameters(this Uri uri, 
                                       NameValueCollection parameters)
    {
        var stringBuilder = new StringBuilder();
        string str = "?";
        for (int index = 0; index < parameters.Count; ++index)
        {
            stringBuilder.Append(str + 
                System.Net.WebUtility.UrlEncode(parameters.AllKeys[index]) +
                 "=" + System.Net.WebUtility.UrlEncode(parameters[index]));
            str = "&";
        }
        return new Uri(uri + stringBuilder.ToString());
    }

    public static string GetBaseUrl(this Uri uri) {
        string baseUrl = uri.Scheme + "://" + uri.Host;
        return baseUrl;
    }

    public static string GetBaseUrl_Path(this Uri uri) {
        string baseUrl = uri.Scheme + "://" + uri.Host + uri.AbsolutePath;
        return baseUrl;
    }
 }

Usage:

用法:

//url -  https://example.com/api/rest/example?firstname=Linus&lastname=Trovalds
Uri myUri = new Uri("https://example.com/api/rest/example").AttachParameters(
            new NameValueCollection
            {
                {"firstname","Linus"},
                {"lastname","Trovalds"}
            }
          );
// https://example.com
string baseUrl = myUri.GetBaseUrl();
// https://example.com/api/rest/example
string baseUrlandPath = myUri.GetBaseUrl_Path();