1

ASP.net core may run on arbitrary number of ports, sometimes the application may run via command line getting passed port as a parameter, sometimes within docker it's running at 80 if profile Released is specified, how can we determine programmatically what port asp.net is actually running on?

A suggested answer is not an answer because that requires access to context and let's say on Startup I need to access this value?

launchSettings.json

"Customer": {
  "commandName": "Project",
  "launchBrowser": false,
  "applicationUrl": "https://localhost:5007;http://localhost:5006",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development",
  }

for instance, in the following code

public static void Main(string[] args)
{
    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Service>();

or anywhere during the system startup process.

AppDeveloper
  • 1,816
  • 7
  • 24
  • 49

1 Answers1

2

You can try get port from ServerAddressesFeature :

public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
{
    var serverAddressesFeature = app.ServerFeatures.Get<IServerAddressesFeature>();
    var address = serverAddressesFeature.Addresses.First();
    int port = int.Parse(address.Split(':').Last());


    logger.LogInformation("Listening on the following addresses: " + string.Join(", ", port.ToString()));
}

As https://github.com/aspnet/Hosting/issues/811 :

That's not going to work for IIS or IIS Express. IIS is running as a reverse proxy. It picks a random port for your process to listen on and does not flow the public address information to you. The only way to get the public address information is from incoming requests.

Nan Yu
  • 26,101
  • 9
  • 68
  • 148
  • Thanks and awesome. +1 for the IIS hiccup, question, is `string.Join(", "` necessary? – AppDeveloper Oct 17 '19 at 15:07
  • Also is there a way to check for if you are running IIS or IIS Express as a guard, so I can just revert to a default port. – AppDeveloper Oct 17 '19 at 15:12
  • string.Join(", " is not necessary .For the second question ,you may check this reply: https://stackoverflow.com/questions/55852820/check-if-hosting-server-is-iis-or-kestrel-at-runtime-in-aspnet-core – Nan Yu Oct 18 '19 at 02:12
  • In my case, `address` was `"http://localhost:52198"` and therefore the int.Parse didn't work and was essentially unnecessary. YMMV. – karfus Jul 18 '22 at 17:52