简体   繁体   中英

How can I get a part/subdomain of my URL in C#?

I have a URL like the following

http://yellowcpd.testpace.net

How can I get yellowcpd from this? I know I can do that with string parsing, but is there a builtin way in C#?

try this

string url = Request.Url.AbsolutePath;
var myvalues= url.Split('.');

Assuming your URLs will always be testpace.net , try this:

var subdomain = Request.Url.Host.Replace("testpace.net", "").TrimEnd('.');

It'll just give you the non- testpace.net part of the Host. If you don't have Request.Url.Host , you can do new Uri(myString).Host instead.

This fits the bill.

Split over two lines:

string rawURL = Request.Url.Host;
string domainName = rawURL .Split(new char[] { '.', '.' })[1];

Or over one:

string rawURL = Request.Url.Host.Split(new char[] { '.', '.' })[1];

The simple answer to your question is no there isn't a built in method to extract JUST the sub-domain. With that said this is the solution that I use...

public enum GetSubDomainOption
{
    ExcludeWWW,
    IncludeWWW
};
public static class Extentions
{
    public static string GetSubDomain(this Uri uri,
        GetSubDomainOption getSubDomainOption = GetSubDomainOption.IncludeWWW)
    {
        var subdomain = new StringBuilder();
        for (var i = 0; i < uri.Host.Split(new char[]{'.'}).Length - 2; i++)
        {
            //Ignore any www values of ExcludeWWW option is set
            if(getSubDomainOption == GetSubDomainOption.ExcludeWWW && uri.Host.Split(new char[]{'.'})[i].ToLowerInvariant() == "www") continue;
            //I use a ternary operator here...this could easily be converted to an if/else if you are of the ternary operators are evil crowd
            subdomain.Append((i < uri.Host.Split(new char[]{'.'}).Length - 3 && 
                              uri.Host.Split(new char[]{'.'})[i+1].ToLowerInvariant() != "www") ?                     
                                   uri.Host.Split(new char[]{'.'})[i] + "." :
                                   uri.Host.Split(new char[]{'.'})[i]);
        }
        return subdomain.ToString();
    }
}

USAGE:

var subDomain = Request.Url.GetSubDomain(GetSubDomainOption.ExcludeWWW);

or

var subDomain = Request.Url.GetSubDomain();

I currently have the default set to include the WWW. You could easilly reverse this by switching the optional parameter value in the GetSubDomain() method.

In my opinion this allows for an option that looks nice in code and without digging in appears to be 'built-in' to c#. Just to confirm your expectations...I tested three values and this method will always return just the "yellowcpd" if the exclude flag is used.

  • www.yellowcpd.testpace.net
  • yellowcpd.testpace.net
  • www.yellowcpd.www.testpace.net

One assumption that I use is that...splitting the hostname on a . will always result in the last two values being the domain (ie something.com)

How can I get yellowcpd from this? I know I can do that with string parsing, but is there a builtin way in C#?

.Net doesn't provide a built-in feature to extract specific parts from Uri.Host. You will have to use string manipulation or a regular expression yourself.

The only constant part of the domain string is the TLD. The TLD is the very last bit of the domain string, eg .com, .net, .uk etc. Everything else under that depends on the particular TLD for its position (so you can't assume the next to last part is the "domain name" as, for .co.uk it would be .co

As others have pointed out, you can do something like this:

var req = new HttpRequest(filename: "search", url: "http://www.yellowcpd.testpace.net", queryString: "q=alaska");
var host = req.Url.Host;
var yellow = host.Split('.')[1];

The portion of the URL you want is part of the hostname. You may hope to find some method that directly addresses that portion of the name, eg "the subdomain (yellowcpd) within TestSpace", but this is probably not possible, because the rules for valid host names allow for any number of labels (see Valid Host Names ). The host name can have any number of labels, separated by periods. You will have to add additional restrictions to get what you want, eg "Separate the host name into labels, discard www if present and take the next label".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM