Get specific subdomain from URL in foo.bar.car.com

后端 未结 7 1761
清酒与你
清酒与你 2020-11-30 10:19

Given a URL as follows:

foo.bar.car.com.au

I need to extract foo.bar.

I came across the following code :

pr         


        
7条回答
  •  抹茶落季
    2020-11-30 10:45

    I faced a similar problem and, based on the preceding answers, wrote this extension method. Most importantly, it takes a parameter that defines the "root" domain, i.e. whatever the consumer of the method considers to be the root. In the OP's case, the call would be

    Uri uri = "foo.bar.car.com.au";
    uri.DnsSafeHost.GetSubdomain("car.com.au"); // returns foo.bar
    uri.DnsSafeHost.GetSubdomain(); // returns foo.bar.car
    

    Here's the extension method:

    /// Gets the subdomain portion of a url, given a known "root" domain
    public static string GetSubdomain(this string url, string domain = null)
    {
      var subdomain = url;
      if(subdomain != null)
      {
        if(domain == null)
        {
          // Since we were not provided with a known domain, assume that second-to-last period divides the subdomain from the domain.
          var nodes = url.Split('.');
          var lastNodeIndex = nodes.Length - 1;
          if(lastNodeIndex > 0)
            domain = nodes[lastNodeIndex-1] + "." + nodes[lastNodeIndex];
        }
    
        // Verify that what we think is the domain is truly the ending of the hostname... otherwise we're hooped.
        if (!subdomain.EndsWith(domain))
          throw new ArgumentException("Site was not loaded from the expected domain");
    
        // Quash the domain portion, which should leave us with the subdomain and a trailing dot IF there is a subdomain.
        subdomain = subdomain.Replace(domain, "");
        // Check if we have anything left.  If we don't, there was no subdomain, the request was directly to the root domain:
        if (string.IsNullOrWhiteSpace(subdomain))
          return null;
    
        // Quash any trailing periods
        subdomain = subdomain.TrimEnd(new[] {'.'});
      }
    
      return subdomain;
    }
    

提交回复
热议问题