How to dynamically change the port listened by Webserver in. NET when the Webserver is running

Aspire 81 Reputation points
2024-05-15T07:45:43.5233333+00:00

I created a NET 8 Console Application to create a WebServer and make it a Windows Service, in Program.cs, the code implementation is as follows

var webOptions = new WebApplicationOptions()
{
    Args = args,
    ContentRootPath = AppContext.BaseDirectory
};
var builder = WebApplication.CreateBuilder(webOptions);
builder.WebHost.UseKestrel(options =>
{
    option.ListenAnyIP(12345);
});
var app = builder.Build();
await app.RunAsync();

What should I do if I want to dynamically change the listening port in ListenAnyIP by reading the Port value in the file? Do I need to call the appStopAsyc() when the port changes and then execute the above settings again?

Regards

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,481 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,254 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 58,356 Reputation points
    2024-05-15T15:43:05.2733333+00:00

    yes. if you want to exit from a request, you can use the injected IApplicationLifetime service StopApplication() method.

    0 comments No comments

  2. Can Kucukgultekin 0 Reputation points
    2024-05-17T21:03:40.89+00:00

    To dynamically change the listening port of an ASP.NET Core web server while it's running, you'll need to implement a mechanism to restart the web server with the new port configuration. Unfortunately, ASP.NET Core's Kestrel web server does not support changing the listening port without restarting the server.

    1. Read the port value from a configuration file.
    2. Watch for changes in the configuration file.
    3. Restart the web server with the new port value when the configuration changes.

    First, create a configuration file appsettings.json to store the port value:

    Use FileSystemWatcher to monitor changes in the configuration file:

    Explanation:

    1. Configuration Loading: The ConfigurationBuilder loads the configuration from appsettings.json, and the configuration is added to the WebApplication builder.
    2. Initial Port Setup: The UseKestrel method reads the initial port value from the configuration.
    3. File System Watcher: A FileSystemWatcher monitors changes to appsettings.json. When the file changes, it stops the current app, reads the new port value, and restarts the app with the new port configuration.
    0 comments No comments