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 -

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

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

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

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

31
32
33
34
35
36
37
38
39
40
41
42
43
//app.Run();

app.Start();

var server = app.Services.GetService<IServer>();
addressFeature = server.Features.Get<IServerAddressesFeature>();

foreach (var address in addressFeature.Addresses)
{
    Console.WriteLine("Kestrel is listening on address: " + address);
}

app.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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

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

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

//app.Run();

app.Start();

var server = app.Services.GetService<IServer>();
addressFeature = server.Features.Get<IServerAddressesFeature>();

foreach (var address in addressFeature.Addresses)
{
    Console.WriteLine("Kestrel is listening on address: " + address);
}

app.WaitForShutdown();

Full source code available here

comments powered by Disqus

Related