3

I am having a requirement to correctly get the domain/subdomain based on the current url. this is required in order to correctly fetch the data from database and further call web api with correct parameters.

In perticular, I am facing issues with local and production urls. for ex.

In local, i have

http://sample.local.example.com 
http://test.dev.example.com

In production, i have

http://client.example.com 
http://program.live.example.com

i need

Subdomain as: sample / test / client / program
Domain as: exmpale 

So far i tried to use c# with following code to identify the same. It works fine on my local but i am sure this will create an issue on production at some point of time. Basically, for Subdomain, get the first part and for Domain, get the last part before ''.com''

 var host = Request.Url.Host;
 var domains = host.Split('.');
 var subDomain = domains[0];
 string mainDomain = string.Empty;
  #if DEBUG
    mainDomain = domains[2]; 
  #else
    mainDomain = domains[1]; 
  #endif

 return Tuple.Create(mainDomain, subDomain);
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
patel.milanb
  • 5,822
  • 15
  • 56
  • 92

3 Answers3

6

Instead of a regex, I think Linq should help your here. Try:

public static (string, string) GetDomains(Uri url)
{
    var domains = url.Host.Substring(0, url.Host.LastIndexOf(".")).Split('.');
    var subDomain = string.Join("/", domains.Take(domains.Length - 1));
    var mainDomain = domains.Last();
    return (mainDomain, subDomain);
}

output for "http://program.live.example.com"

example
program/live

Try it Online!

aloisdg
  • 22,270
  • 6
  • 85
  • 105
2

This regex should work for you:

Match match = Regex.Match(temp, @"http://(\w+)\.?.*\.(\w+).com$");

string subdomain = match.Groups[1].Value;
string domain = match.Groups[2].Value;

http://(\w+)\. matches 1 or more word characters as group 1 before a dot and after http://

.* matches zero or more occurences of any character

\.(\w+).com matches 1 or more word characters as group 2 before .com and after a dot

$ specifies the end of the string

\.? makes the dot optional to catch the case if there is nothing between group 1 and 2 like in http://client.example.com

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
1

You are doing the right and you can get the domain name as the second last value in the array.

var host = Request.Url.Host;
var domains = host.Split('.');
string subDomain = domains[0].Split('/')[2];
string mainDomain = domains[domains.Length-2];  
return Tuple.Create(mainDomain, subDomain);

If you want all the subdomains you can put a loop here.

MarvMan
  • 41
  • 9
Amit chauhan
  • 540
  • 9
  • 22