Reputation: 47377
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.
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.
Upvotes: 13
Views: 5960
Reputation: 19781
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);
}
Upvotes: 13
Reputation: 47377
Here's the idea that I've come up with.
@SLaks, I'd love to here your thoughts on this.
''# 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
Upvotes: 0
Reputation: 887453
See here for a list of suffixes that allow arbitrary registrations.
Find the longest suffix of the full domain name in that list, then return everything after the last .
before that suffix.
Upvotes: 2
Reputation: 15069
Get a list of top level domains, and match every domain with that list, taking only 1 word after the match.
(you might need to add some support for .co. ect...
Upvotes: 0