55
66using System ;
77using System . Diagnostics ;
8+ using System . Linq ;
89using System . Threading ;
910using System . Threading . Tasks ;
1011using Datadog . Demos . Util ;
1112using Microsoft . AspNetCore . Hosting ;
12- using Microsoft . Extensions . Configuration ;
13+ using Microsoft . AspNetCore . Hosting . Server ;
14+ using Microsoft . AspNetCore . Hosting . Server . Features ;
1315using Microsoft . Extensions . Hosting ;
1416
1517namespace Samples . Website_AspNetCore01
@@ -46,20 +48,6 @@ public static async Task Main(string[] args)
4648 WriteLine ( $ "host built in { sw . ElapsedMilliseconds } ms") ;
4749 sw . Restart ( ) ;
4850
49- // ASP.NET Core accepts listening url via what is set by Visual Studio
50- // (from the launchsettings.json). It could be overriden by --Urls
51- // on the command line
52- var configuration = host . Services . GetService ( typeof ( IConfiguration ) ) as IConfiguration ;
53- var rootUrl = configuration [ "Urls" ] ;
54-
55- // otherwise, use the default ASP.NET Core value
56- if ( string . IsNullOrEmpty ( rootUrl ) )
57- {
58- rootUrl = "http://localhost:5000" ;
59- }
60-
61- WriteLine ( $ "Listening to { rootUrl } ") ;
62-
6351 var cts = new CancellationTokenSource ( ) ;
6452 using ( var selfInvoker = new SelfInvoker ( cts . Token ) )
6553 {
@@ -72,6 +60,12 @@ public static async Task Main(string[] args)
7260 sw . Stop ( ) ;
7361 WriteLine ( $ "host started in { sw . ElapsedMilliseconds } ms") ;
7462
63+ // Read the address Kestrel actually bound (after StartAsync). Configuration["Urls"]
64+ // may be "http://127.0.0.1:0" when the test runner asks for a dynamic port, so the
65+ // bound address is the only reliable source of the real listening URL.
66+ var rootUrl = GetBoundRootUrl ( host ) ;
67+ WriteLine ( $ "Listening to { rootUrl } ") ;
68+
7569 WriteLine ( ) ;
7670 WriteLine ( $ "Started at { DateTime . UtcNow } .") ;
7771
@@ -107,6 +101,13 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
107101 webBuilder . UseStartup < Startup > ( ) ;
108102 } ) ;
109103
104+ private static string GetBoundRootUrl ( IHost host )
105+ {
106+ var server = ( IServer ) host . Services . GetService ( typeof ( IServer ) ) ;
107+ var address = server ? . Features . Get < IServerAddressesFeature > ( ) ? . Addresses . FirstOrDefault ( ) ;
108+ return string . IsNullOrEmpty ( address ) ? "http://localhost:5000" : address . TrimEnd ( '/' ) ;
109+ }
110+
110111 // Helper method to output both to the console (when the app runs in the console)
111112 // and via Trace to see them while running under IISExpress both in Visual Studio
112113 // or with SysInternals DebugView (https://docs.microsoft.com/en-us/sysinternals/downloads/debugview)
0 commit comments