Skip to content

Commit d798b65

Browse files
authored
ServiceEndpoint.ToString(): omit zero port (dotnet#4015)
1 parent f552a0d commit d798b65

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/Microsoft.Extensions.ServiceDiscovery.Abstractions/Internal/ServiceEndpointImpl.cs

+4
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,13 @@ namespace Microsoft.Extensions.ServiceDiscovery.Internal;
99
internal sealed class ServiceEndpointImpl(EndPoint endPoint, IFeatureCollection? features = null) : ServiceEndpoint
1010
{
1111
public override EndPoint EndPoint { get; } = endPoint;
12+
1213
public override IFeatureCollection Features { get; } = features ?? new FeatureCollection();
14+
1315
public override string? ToString() => EndPoint switch
1416
{
17+
IPEndPoint ip when ip.Port == 0 => $"{ip.Address}",
18+
DnsEndPoint dns when dns.Port == 0 => $"{dns.Host}",
1519
DnsEndPoint dns => $"{dns.Host}:{dns.Port}",
1620
_ => EndPoint.ToString()!
1721
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Net;
5+
using Xunit;
6+
7+
namespace Microsoft.Extensions.ServiceDiscovery.Tests;
8+
9+
public class ServiceEndpointTests
10+
{
11+
public static TheoryData<EndPoint> ZeroPortEndPoints => new()
12+
{
13+
IPEndPoint.Parse("127.0.0.1:0"),
14+
new DnsEndPoint("microsoft.com", 0),
15+
new UriEndPoint(new Uri("https://microsoft.com"))
16+
};
17+
18+
public static TheoryData<EndPoint> NonZeroPortEndPoints => new()
19+
{
20+
IPEndPoint.Parse("127.0.0.1:8443"),
21+
new DnsEndPoint("microsoft.com", 8443),
22+
new UriEndPoint(new Uri("https://microsoft.com:8443"))
23+
};
24+
25+
[Theory]
26+
[MemberData(nameof(ZeroPortEndPoints))]
27+
public void ServiceEndpointToStringOmitsUnspecifiedPort(EndPoint endpoint)
28+
{
29+
var serviceEndpoint = ServiceEndpoint.Create(endpoint);
30+
var epString = serviceEndpoint.ToString();
31+
Assert.DoesNotContain(":0", epString);
32+
}
33+
34+
[Theory]
35+
[MemberData(nameof(NonZeroPortEndPoints))]
36+
public void ServiceEndpointToStringContainsSpecifiedPort(EndPoint endpoint)
37+
{
38+
var serviceEndpoint = ServiceEndpoint.Create(endpoint);
39+
var epString = serviceEndpoint.ToString();
40+
Assert.Contains(":8443", epString);
41+
}
42+
}

0 commit comments

Comments
 (0)