2

I need to check whether the current URL has the subdomain name and if it has the subdomain, I want extract it from the URL.

Could anyone konw how to do this in the C# in an ASP.NET MVC app.

Thanks.

Ravi
  • 1,293
  • 6
  • 20
  • 31

3 Answers3

3

Is this what you're looking for?

Uri fullPath = new Uri("http://subdomain.domain.topleveldomain/index.html");

string hostname = fullPath.Host; // returns "subdomain.domain.topleveldomain"

char[] separators = new char[]{'.'};

// returns {"subdomain","domain","topleveldomain"}
string[] domains = hostname.Split(separators); 

string subdomain = domains[0];
string domain = domains[1];
string tld = domains[2];

String.Split documentation

Note that you'll need to change it a bit if it's possible there will be more than one subdomain, I.E. http://subsub.sub.dom.tld/ or something like that.

Tim R.
  • 1,570
  • 2
  • 15
  • 33
2

You can't do that, consider these examples, one is a domain and other is subdomain

domain.co.uk

subdomain.hp.hr

co.uk is United Kingdom TLD

and hp.hr could be Hewlett-Packard site registered in Croatia

Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102
0

Subdomain in what sense exactly?

You could do:

Uri u = new Uri("http://sub.mydomain.com/path/file.htm");
if(i.Host == "sub.mydomain.com")
{ ... }

Is that what you want?

tyranid
  • 13,028
  • 1
  • 32
  • 34
  • It is not any specific subdomain name I'm looking for. I need to check whether the URL has any subdomain name – Ravi Nov 20 '09 at 07:03
  • But sub-domain from a particular domain? As in technically .com is the top level domain so mydomain is a subdomain :) If you want say anything under mydomain.com then just do a Regex match on [^.]+\.mydomain\.com and if it matches it has at least one sub domain off mydomain.com – tyranid Nov 20 '09 at 07:13
  • Oh you want a $ at the end of the regex to match to end of the string ;) – tyranid Nov 20 '09 at 07:13
  • Assuming that you do know the primary domain, you could do something like: if(u.split(".")[0] != "mydomain") { // it is a subdomain }. You could also exclude "www" or anything else you don't want to match. Note that my C# is rusty, so this may not be the exact right syntax... – Brian Moeskau Nov 20 '09 at 07:21