简体   繁体   English

获取没有端口.net的地址,并将地址+端口构造到端点

[英]Get Address without the port .net and construct address + port to an endpoint

From a URL like " http://localhost:2111/ " How to separate the address part : http://localhost/ from the port part: 2111? 从像“ http://localhost:2111/ ”这样的URL如何分离地址部分: http://localhost/来自端口部分:2111? Is there a data structure that allow me to separate or construct http://localhost:2111/ to/from its address and port? 是否有一个数据结构允许我从其地址和端口分离或构造http://localhost:2111/

Use this: 用这个:

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

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

To do the opposite: 做相反的事情:

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

For me uri.Ports returns 80 , I don't know if it works for you but give it a try. 对我来说uri.Ports返回80 ,我不知道它是否适合你,但尝试一下。

UriBuilder can be used to remove the port from the url by setting its port value to either -1 or 80: 通过将端口值设置为-1或80,可以使用UriBuilder从URL中删除端口:

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

The above will output http://localhost/ . 以上将输出http://localhost/

If you want to add them back together then use UriBuilder again and set the port to 2111: 如果要将它们重新组合在一起,请再次使用UriBuilder并将端口设置为2111:

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

The above will output http://localhost/2111 . 以上将输出http://localhost/2111

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

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