@@ -207,6 +207,19 @@ public static void MarkPortAsUsed(int port)
207207 ap [ port ] = true ;
208208 }
209209
210+ public static bool TryMarkPortAsUsed ( int port )
211+ {
212+ ArgumentOutOfRangeException . ThrowIfLessThan ( port , 1 , nameof ( port ) ) ;
213+ ArgumentOutOfRangeException . ThrowIfGreaterThan ( port , 65535 , nameof ( port ) ) ;
214+ var ap = AllocatedPorts ;
215+ if ( ap [ port ] )
216+ {
217+ return false ; // Port is already allocated
218+ }
219+ ap [ port ] = true ;
220+ return true ; // Successfully marked the port as used
221+ }
222+
210223 public static int GetRandomFreePort ( int minPort , int maxPort )
211224 {
212225 var ap = AllocatedPorts ;
@@ -322,13 +335,13 @@ internal static void ShowIISExpressHttpsEndpointInformation<T>(this T resource,
322335 } ) ;
323336 }
324337
325- internal static EndpointAnnotation AddOrUpdateEndpointFromBinding ( this IResourceWithEndpoints resource , Binding binding )
338+ internal static EndpointAnnotation AddOrUpdateEndpointFromBinding ( this IResourceWithEndpoints resource , Binding binding , ILogger ? logger = null )
326339 {
327340 var hostName = string . IsNullOrEmpty ( binding . HostName ) ? "localhost" : binding . HostName ;
328341
329342 var endpoint = resource . Annotations
330343 . OfType < EndpointAnnotation > ( )
331- . Where ( ea => StringComparer . OrdinalIgnoreCase . Equals ( ea . Name , binding . Protocol ) &&
344+ . Where ( ea => StringComparer . OrdinalIgnoreCase . Equals ( ea . Name , binding . Protocol ) &&
332345 StringComparer . OrdinalIgnoreCase . Equals ( ea . TargetHost , hostName ) )
333346 . SingleOrDefault ( ) ;
334347 if ( endpoint is null )
@@ -341,15 +354,24 @@ internal static EndpointAnnotation AddOrUpdateEndpointFromBinding(this IResource
341354 endpoint = new EndpointAnnotation ( System . Net . Sockets . ProtocolType . Tcp , name : $ "{ binding . Protocol } -{ binding . Port } -{ hostName } ") ;
342355 resource . Annotations . Add ( endpoint ) ;
343356 }
344- if ( StringComparer . OrdinalIgnoreCase . Equals ( hostName , "localhost" ) )
357+ if ( StringComparer . OrdinalIgnoreCase . Equals ( hostName , "localhost" ) )
345358 {
346359 MarkPortAsUsed ( binding . Port ) ;
347360 }
361+ else
362+ {
363+ if ( ! TryMarkPortAsUsed ( binding . Port ) )
364+ {
365+ logger ? . LogWarning ( "Port {Port} is already allocated. Ensure each binding has a unique hostName." , binding . Port ) ;
366+ }
367+ logger ? . LogInformation ( "It is recommended to use 'localhost' with unique ports for IIS Express endpoints to avoid port conflicts." ) ;
368+ // If the hostName is not localhost, we disable the proxy support so that SNI and host name routing works as expected.
369+ endpoint . IsProxied = false ;
370+ }
348371
349372 endpoint . TargetPort = binding . Port ;
350373 endpoint . TargetHost = hostName ;
351374 endpoint . UriScheme = binding . Protocol ;
352- //endpoint.IsProxied = false;
353375
354376 return endpoint ;
355377 }
0 commit comments