Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: How can I get the domain name without any subdomains?

Tags:

.net

dns

I've been searching here on SO but I can't seem to find the answer to this question. I'm having a heck of a time figuring out if there's a method that will give me just the main domain from the 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 a bit. This is for use on my own domains only and not going to be used on every domain in existence.
There's currently three suffixes that I need to be able to deal with.

  • .com
  • .ca
  • .local
like image 860
Chase Florell Avatar asked Jan 02 '11 23:01

Chase Florell


People also ask

Can you have a subdomain without a domain?

A subdomain is an add-on to your primary domain name. Essentially, a subdomain is a separate part of your website that operates under the same primary domain name. To create a subdomain, you must have a primary domain name. Without a primary domain name, there's no way to add a subdomain onto it.


1 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);
}
like image 131
sisve Avatar answered Nov 10 '22 04:11

sisve