2015-06-22 36 views
-3

什麼是解析域和可選的子域,使用C#解析URL的最佳方式。該解決方案還應該與「本地主機」一起工作,以便相同的代碼可以用於本地開發和生產中。如何從使用C#的URL解析域和子域(如果存在)?

例子和預期結果:

http(s)://yahoo.com -> domain:yahoo.com | subdomain: 
    http(s)://test.yahoo.com -> domain:yahoo.com | subdomain:test 
    http(s)://test.testing.yahoo.com -> domain:yahoo.com | subdomain:test.testing 
    http(s)://localhost:55555 -> domain:localhost | subdomain: 
    http(s)://test.localhost:55555 -> domain:localhost | subdomain:test 
    http(s)://test.testing.localhost:55555 -> domain:localhost | subdomain:test.testing 
    http(s)://yahoo.com.uk -> domain:yahoo.com.uk | subdomain: 
    http(s)://test.yahoo.com.uk -> domain:yahoo.com.uk | subdomain:test 
+3

什麼定義了'這裏subdomain'?你的例子看起來很隨意。 – DavidG

+1

此線程爲您的需求提供了一種可能的擴展方法: http://stackoverflow.com/questions/19734769/get-specific-subdomain-from-url-in-foo-bar-car-com – tendrel

+0

我喜歡擴展方法。不知道它是否適用於我的本地主機場景。 DavidG提到了另一種場景,其中有多部分域可能無法使用它。我將不得不玩,看看。 – wgpubs

回答

2

有沒有辦法來確定您的子域名是什麼,例如:

www.yahoo.com 
www2.yahoo.com 

wwwwww2子域?那麼newcastle.sch.uk呢?這是一個域,而不是一個子域。那麼新的.uk頂級域名呢?

至於其他部件,我將使用Uri類是這樣的:

var url = "http://[email protected]:1234"; 
var uri = new Uri(url); 

Console.WriteLine(uri.Host); 
Console.WriteLine(uri.Port); 
Console.WriteLine(uri.Scheme); 
Console.WriteLine(uri.UserInfo); 

這將輸出:

test.somedomain.com 
1234 
http 
someuser 
+0

至於你的第一個問題:是的,www和www2都將被視爲子域名。至於你的第二個問題,好點。在這種情況下,域名應該回來「newcastle.sch.uk」,子域名爲空。 – wgpubs

+2

我的觀點主要是這些只是我頭頂的幾個例子。爲了保證你知道什麼是子域,你需要知道什麼是頂級域名。 – DavidG