Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to determine programmatically what port asp.net core is running on

Tags:

asp.net-core

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.

like image 544
AppDeveloper Avatar asked Dec 18 '25 22:12

AppDeveloper


1 Answers

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.

like image 166
Nan Yu Avatar answered Dec 21 '25 22:12

Nan Yu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!