views:

473

answers:

3

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.

A: 

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
It is not any specific subdomain name I'm looking for. I need to check whether the URL has any subdomain name
Ravi
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
Oh you want a $ at the end of the regex to match to end of the string ;)
tyranid
Should be if(u.Host...)
bmoeskau
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...
bmoeskau
+1  A: 

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.
Yep, those pesky .co.uk domains messing up your schemes ;)
Zhaph - Ben Duguid