2013-04-09 19 views
1

從URL如「http://localhost:2111/」如何將端口部分的地址部分:http://localhost/分開:2111?是否有數據結構允許我將http://localhost:2111/分開或構建到其地址和端口?獲取不帶端口.net的地址,並將地址+端口構造到端點

+0

看看'Uri'類。 – leppie 2013-04-09 07:53:00

+0

@leppie似乎我不能從'http:// localhost /'和2111 – 2013-04-09 07:57:35

+0

構建'http:// localhost:2111 /'爲什麼你不能? – leppie 2013-04-09 08:00:49

回答

2

使用此:

Uri uri = new Uri("http://localhost:2111/"); 
string newUri = uri.Scheme + "://" + uri.Host + "/"; 
Console.WriteLine(newUri); 

// Output: 
// http://localhost/ 

要反其道而行之:

Uri uri = new Uri("http://localhost/"); 
string newURI = uri.AbsoluteUri + uri.Port; 

對我來說uri.Ports回報80,我不知道它是否適合你,但給它一個嘗試。

+0

如何做到相反? – 2013-04-09 08:00:13

+0

「對面」是什麼意思? – Andy 2013-04-09 08:00:54

+0

從'http:// localhost /'構建'http:// localhost:2111 /'和2111 – 2013-04-09 08:01:44

1

UriBuilder可用於通過其端口值設置爲-1或80以除去從URL中的端口:

var uriBuilder = new UriBuilder("http://localhost:2111/"); 
uriBuilder.Port = -1; // or 80 
string newUrl = uriBuilder.Uri.AbsoluteUri; 
Console.WriteLine(newUrl); 

上面將輸出http://localhost/

如果你想將它們添加端口一起回來,然後再使用UriBuilder,並設置爲2111:

var uriBuilder = new UriBuilder("http://localhost/"); 
uriBuilder.Port = 2111; 
string newUrl = uriBuilder.Uri.AbsoluteUri; 
Console.WriteLine(newUrl); 

上面會輸出http://localhost/2111