yes. if you want to exit from a request, you can use the injected IApplicationLifetime service StopApplication() method.
How to dynamically change the port listened by Webserver in. NET when the Webserver is running
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
2 answers
Sort by: Most helpful
-
-
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.
- Read the port value from a configuration file.
- Watch for changes in the configuration file.
- 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:
- Configuration Loading: The
ConfigurationBuilder
loads the configuration fromappsettings.json
, and the configuration is added to theWebApplication
builder. - Initial Port Setup: The
UseKestrel
method reads the initial port value from the configuration. - File System Watcher: A
FileSystemWatcher
monitors changes toappsettings.json
. When the file changes, it stops the current app, reads the new port value, and restarts the app with the new port configuration.