Get host domain from URL?

001 picture 001 · Jan 8, 2013 · Viewed 212.9k times · Source

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

Adil picture Adil · Jan 8, 2013

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"