2013-04-09 64 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