Programmatically Determine what Ports Kestrel is Running On

Full source code available here

In the previous blog post I showed a few ways to set the ports Kestrel will use.

In this post, I’ll show how to programmatically determine what ports it is running on.

Starting, instead of Running the application

The default template for a .NET 6 Web API application uses app.Run as the last line of the Program.cs.

You are going to use app.Start(), and app.WaitForShutdown() instead. And between those two you will find out what ports Kestrel is running on.

First, add two using statements -

1using Microsoft.AspNetCore.Hosting.Server;
2using Microsoft.AspNetCore.Hosting.Server.Features;

Below var app = builder.Build(); add -

22IServerAddressesFeature addressFeature = null;
23app.MapGet("/", () => $"Hi there, Kestrel is running on\n\n{string.Join("\n", addressFeature.Addresses.ToArray() )} ");

And finally, instead of app.Run(), use this -

31//app.Run();
32
33app.Start();
34
35var server = app.Services.GetService<IServer>();
36addressFeature = server.Features.Get<IServerAddressesFeature>();
37
38foreach (var address in addressFeature.Addresses)
39{
40    Console.WriteLine("Kestrel is listening on address: " + address);
41}
42
43app.WaitForShutdown();

That’s it, now fire up the application, it will print out the ports to the command line (you were getting that by default anyway), but now when you go to http://localhost:5298, you will see -

Hi there, Kestrel is running on

https://localhost:7298
http://localhost:5298 

Full Source Code

For completeness here is the full source code.

 1using Microsoft.AspNetCore.Hosting.Server;
 2using Microsoft.AspNetCore.Hosting.Server.Features;
 3
 4var builder = WebApplication.CreateBuilder(args);
 5
 6// Add services to the container.
 7
 8builder.Services.AddControllers();
 9// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
10builder.Services.AddEndpointsApiExplorer();
11builder.Services.AddSwaggerGen();
12
13var app = builder.Build();
14
15// Configure the HTTP request pipeline.
16if (app.Environment.IsDevelopment())
17{
18    app.UseSwagger();
19    app.UseSwaggerUI();
20}
21
22IServerAddressesFeature addressFeature = null;
23app.MapGet("/", () => $"Hi there, Kestrel is running on\n\n{string.Join("\n", addressFeature.Addresses.ToArray() )} ");
24
25app.UseHttpsRedirection();
26
27app.UseAuthorization();
28
29app.MapControllers();
30
31//app.Run();
32
33app.Start();
34
35var server = app.Services.GetService<IServer>();
36addressFeature = server.Features.Get<IServerAddressesFeature>();
37
38foreach (var address in addressFeature.Addresses)
39{
40    Console.WriteLine("Kestrel is listening on address: " + address);
41}
42
43app.WaitForShutdown();

Full source code available here

comments powered by Disqus

Related