177

文字列 URL からホスト ドメインを取得する方法は?

GetDomain には 1 つの入力「URL」、1 つの出力「ドメイン」があります。

例1

INPUT: http://support.domain.com/default.aspx?id=12345
OUTPUT: support.domain.com

例2

INPUT: http://www.domain.com/default.aspx?id=12345
OUTPUT: www.domain.com

例3

INPUT: http://localhost/default.aspx?id=12345
OUTPUT: localhost
4

10 に答える 10

314

You can use Request object or Uri object to get host of url.

Using Request.Url

string host = Request.Url.Host;

Using Uri

Uri myUri = new Uri("http://www.contoso.com:8080/");   
string host = myUri.Host;  // host is "www.contoso.com"
于 2013-01-08T09:37:51.220 に答える
81

このようにしてみてください。

Uri.GetLeftPart( UriPartial.Authority )

Uri.GetLeftPart メソッドの URI の部分を定義します。


http://www.contoso.com/index.htm?date=today --> http://www.contoso.com

http://www.contoso.com/index.htm#main --> http://www.contoso.com

nntp://news.contoso.com/123456@contoso.com --> nntp://news.contoso.com

file://server/filename.ext --> file://server

Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));

Demo

于 2013-01-08T09:41:01.607 に答える
30

Uriクラスを使用し、Hostプロパティを使用する

Uri url = new Uri(@"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);
于 2013-01-08T09:39:17.597 に答える
3
 var url = Regex.Match(url, @"(http:|https:)\/\/(.*?)\/");

INPUT = "https://stackoverflow.com/questions/";

OUTPUT = "https://stackoverflow.com/";

于 2020-08-21T19:48:41.920 に答える
1

Try this

Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));

It will output support.domain.com

Or try

Uri.GetLeftPart( UriPartial.Authority )
于 2013-01-08T09:37:59.313 に答える
0

文字列をURIオブジェクトとして構築する必要があり、 Authorityプロパティは必要なものを返します。

于 2013-01-08T09:42:59.540 に答える
-3

WWW はエイリアスなので、ドメインが必要な場合は必要ありません。文字列から実際のドメインを取得するための私のlitllte関数は次のとおりです

private string GetDomain(string url)
    {
        string[] split = url.Split('.');
        if (split.Length > 2)
            return split[split.Length - 2] + "." + split[split.Length - 1];
        else
            return url;

    }
于 2015-03-27T16:20:38.443 に答える