简体   繁体   English

如何在C#中获取URL的部分/子域?

[英]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? 如何从中获取yellowcpd I know I can do that with string parsing, but is there a builtin way in C#? 我知道我可以使用字符串解析来做到这一点,但是C#有内置的方法吗?

try this 尝试这个

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

Assuming your URLs will always be testpace.net , try this: 假设您的网址始终是testpace.net ,请尝试以下操作:

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

It'll just give you the non- testpace.net part of the Host. 它只为您提供主机的testpace.net部分。 If you don't have Request.Url.Host , you can do new Uri(myString).Host instead. 如果您没有Request.Url.Host ,则可以执行new Uri(myString).Host

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. 我目前已默认设置为包括WWW。 You could easilly reverse this by switching the optional parameter value in the GetSubDomain() method. 您可以通过在GetSubDomain()方法中切换可选参数值来GetSubDomain()地做到这一点。

In my opinion this allows for an option that looks nice in code and without digging in appears to be 'built-in' to c#. 在我看来,这允许在代码中看起来不错的选项,而无需深入挖掘,似乎是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. 只是为了确认您的期望...我测试了三个值,如果使用了exclude标志,此方法将始终仅返回“ yellowcpd”。

  • www.yellowcpd.testpace.net www.yellowcpd.testpace.net
  • yellowcpd.testpace.net yellowcpd.testpace.net
  • www.yellowcpd.www.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) 总是会导致最后两个值成为域(即something.com)

How can I get yellowcpd from this? 如何从中获取yellowcpd? I know I can do that with string parsing, but is there a builtin way in C#? 我知道我可以使用字符串解析来做到这一点,但是C#有内置的方法吗?

.Net doesn't provide a built-in feature to extract specific parts from Uri.Host. .Net没有提供从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. 域字符串的唯一恒定部分是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 TLD是域字符串的最后一位,例如.com,.net,.uk等。其下的所有其他内容都取决于特定TLD的位置(因此,您不能假设倒数第二个部分是“域名”,因为对于.co.uk,它将是.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. 所需的URL部分是主机名的一部分。 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 ). 您可能希望找到一些直接解决名称部分的方法,例如“ TestSpace中的子域(yellowcpd)”,但这可能是不可能的,因为有效主机名的规则允许使用任意数量的标签(请参见有效主机名 )。 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". 您将必须添加其他限制才能获得所需的内容,例如“将主机名分隔为标签,如果存在则丢弃www,然后使用下一个标签”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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