001 001 - 4 months ago 33
C# Question

Get host domain from URL?

how to get host domain from a string URL?

GetDomain has 1 input "URL", 1 Output "Domain"

Example1

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


Example2

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


Example3

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

Answer

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"