从URL中获取主机域名?

203

如何从字符串URL中获取主机域名?

GetDomain有1个输入"URL",1个输出"Domain"

示例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

看起来问题是针对URL中的_host_,而不是主机的域名,除非我完全误解了“主机域名”(而不只是“主机”)。答案类似于Uri.Host的事实支持问题应该更新以更好地反映并与问题中所需示例和接受的答案保持一致。 - NoOneSpecial
12个回答

350
你可以使用Request对象或Uri对象来获取URL的主机名。
使用Request.Url
string host = Request.Url.Host;

使用Uri

Uri myUri = new Uri("http://www.contoso.com:8080/");   
string host = myUri.Host;  // host is "www.contoso.com"

2
嗨,我想使用Request.Url,但是Visual Studio仍然返回无法解析符号'Request'的错误。我不知道问题出在哪里。我使用的是Visual Studio 2010和Net Framework 4.0。有人能够解释一下这种情况吗?谢谢。 - Michal
1
你需要有可用的Request对象,通常在网页/服务中可以使用,但默认情况下不适用于其后面。如果没有可用的Request对象,则可以使用Uri类。 - Adil

95

试试这样做:

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


30

使用Uri类并使用Host属性。

Uri url = new Uri(@"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);

21

尝试以下语句

 Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
 string pathQuery = myuri.PathAndQuery;
 string hostName = myuri.ToString().Replace(pathQuery , "");

例子1

 Input : http://localhost:4366/Default.aspx?id=notlogin
 Ouput : http://localhost:4366

例子2

 Input : http://support.domain.com/default.aspx?id=12345
 Output: support.domain.com

如果 myuri.PathAndQuery 是 "/",它只会将其替换为 "",并不起作用。 - Patrick from NDepend team

13

最佳且正确的方式是使用Uri.Authority字段

加载并像下面这样使用Uri:

Uri NewUri;

if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
     Console.Writeline(NewUri.Authority);
}

Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com

Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com

Input : http://localhost/default.aspx?id=12345
Output : localhost

如果您想操作URL,使用Uri对象是一个好的方式。

https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx

3
 var url = Regex.Match(url, @"(http:|https:)\/\/(.*?)\/");

输入 = "https://stackoverflow.com/questions/";

输出 = "https://stackoverflow.com/";


1

试试这个

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

它将输出 support.domain.com

或者尝试

Uri.GetLeftPart( UriPartial.Authority )

0
    public static string DownloadImage(string URL, string MetaIcon,string folder,string name)
    {
        try
        {
            WebClient oClient = new WebClient();

            string LocalState = Windows.Storage.ApplicationData.Current.LocalFolder.Path;

            string storesIcons = Directory.CreateDirectory(LocalState + folder).ToString();

            string path = Path.Combine(storesIcons, name + ".png");

            
            //si la imagen no es valida ej "/icon.png"
            if (!TextBoxEvent.IsValidURL(MetaIcon))
            {
                Uri uri = new Uri(URL);
                string DownloadImage = "https://" + uri.Host + MetaIcon;

                oClient.DownloadFile(new Uri(DownloadImage), path);
            }
            //si la imagen tiene todo ej https://www.mercadolibre.com/icon.png
            else
            {
                oClient.DownloadFile(new Uri(MetaIcon), path);
            }

            return path;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

0

这里有一个适用于所有类型URL的解决方案。

public string GetDomainFromUrl(string url)
{
    url = url.Replace("https://", "").Replace("http://", "").Replace("www.", ""); //Remove the prefix
    string[] fragments = url.Split('/');
    return fragments[0];
}

0

只需要域名 (www.bla.com -> bla)

不需要Uri

static string GetDomainNameOnly(string s)
    {
        string domainOnly = "";
        if (!string.IsNullOrEmpty(s))
        {
            if (s.Contains("."))
            {
                string domain = s.Substring(s.LastIndexOf('.', s.LastIndexOf('.') - 1) + 1);
                string countryDomain = s.Substring(s.LastIndexOf('.'));
                domainOnly = domain.Replace(countryDomain, "");
            }
            else
                domainOnly = s;
        }
        return domainOnly;
    }

这不是被要求的内容。域名应该包含www和.com。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接