Skip to content

Commit e818e1d

Browse files
committed
Attempt to fix it again
1 parent 589385f commit e818e1d

1 file changed

Lines changed: 16 additions & 15 deletions

File tree

  • profiler/src/Demos/Samples.Website-AspNetCore01

profiler/src/Demos/Samples.Website-AspNetCore01/Program.cs

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@
55

66
using System;
77
using System.Diagnostics;
8+
using System.Linq;
89
using System.Threading;
910
using System.Threading.Tasks;
1011
using Datadog.Demos.Util;
1112
using Microsoft.AspNetCore.Hosting;
12-
using Microsoft.Extensions.Configuration;
13+
using Microsoft.AspNetCore.Hosting.Server;
14+
using Microsoft.AspNetCore.Hosting.Server.Features;
1315
using Microsoft.Extensions.Hosting;
1416

1517
namespace 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

Comments
 (0)