【问题标题】:Get Address without the port .net and construct address + port to an endpoint获取没有端口 .net 的地址并构造地址 + 端口到端点
【发布时间】:2013-04-09 07:52:01
【问题描述】:

来自“http://localhost:2111/”之类的 URL 如何将地址部分:http://localhost/ 与端口部分:2111 分开?是否有一种数据结构可以让我将http://localhost:2111/ 与它的地址和端口分开或构造?

【问题讨论】:

  • 查看Uri类。
  • @leppie 好像不能从http://localhost/和2111构造http://localhost:2111/
  • @leppie Port 在 Uri 中是只读的
  • 然后看UriBuilder :)
  • @leppie 这对我有用!如果您愿意,可以将其作为答案:)

标签: c# .net url port


【解决方案1】:

使用这个:

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.Portsreturns 80,我不知道它是否适合你,但试试看。

【讨论】:

  • “相反”是什么意思?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-01-08
    • 2014-12-29
    • 2014-12-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多