Reputation: 2210
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.
Upvotes: 3
Views: 5727
Reputation: 27578
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.
Upvotes: 2