ASP.NET: how to get a domain name without any subdomains?

I searched here for SO, but I can not find the answer to this question. I have damn time to find out if there is a method that will give me only the main domain from HttpContext.Current.Request.Url?

Examples:

http://www.example.com > example.com
http://test.example.com > example.com
http://example.com >example.com

Thanks in advance.

Edit

just to clarify. This is used only for my own domains and will not be used for every existing domain.
There are currently three suffixes that I need to deal with.

  • .com
  • .ca
  • .local
+5
source share
4 answers
public static void Main() {
    var uri = new Uri("http://test.example.com");

    var fullDomain = uri.GetComponents(UriComponents.Host, UriFormat.SafeUnescaped);
    var domainParts = fullDomain
        .Split('.') // ["test", "example", "com"]
        .Reverse()  // ["com", "example", "test"]
        .Take(2)    // ["com", "example"]
        .Reverse(); // ["example", "com"]
    var domain = String.Join(".", domainParts);
}
+5

. , .

, . .

+1

Get a list of top-level domains and match each domain with this list using only one word after the match.

(you may need additional support .co. ect ...

0
source

Here is an idea that I came up with.
@SLaks, I would like your thoughts on this here.

    ''# First we fix the StackOverflow code coloring issue.
    <Extension()>
    Public Function PrimaryDomain(ByVal url As Uri) As String

        If url.Host.Contains("example.com") Then Return "example.com"
        If url.Host.Contains("example.ca") Then Return "example.ca"
        If url.Host.Contains("example.local") Then Return "example.local"
        If url.Host.Contains("localhost") Then Return "localhost"

        Throw New Exception("The url host was not recognized as a known host name for this domain.")
    End Function
0
source

All Articles