Yesterday I had to come up with a method that retrieved the subdomain from the current
web request on an ASP.NET website. I thought that the System.Uri class contained that
information in an easy retrievable way, but no.

Here’s what I came up with instead. It still uses the System.Uri to find the subdomain.

///<summary>

/// Retrieves
the subdomain from the specified URL.

///</summary>

///<param
name="url">The
URL from which to retrieve the subdomain.</param>

///<returns>The
subdomain if it exist, otherwise null.</returns>

privatestaticstring GetSubDomain(Uri url)

{

string host
= url.Host;

if (host.Split('.').Length
> 1)

{

int index
= host.IndexOf(".");

return host.Substring(0,
index);

}

returnnull;

}

To use it, simply put in the URL of your choice like so:

GetSubDomain(Request.Url);

Update

Based on the comments I've had so far on this post, I've made some changes to the
GetSubDomain() method as shown below. Thanks to Anders and Jacob for the comments.

/// Retrieves
the subdomain from the specified URL.

///</summary>

///<param
name="url">The
URL from which to retrieve the subdomain.</param>