Andrew Stakhov
Andrew Stakhov

Reputation: 1135

How to dynamically add/remove additional listen URLs to Kestrel at runtime after server is started?

I want to be able to add/remove ports on the Kestrel listens on after the web server has been started (something you would normally configure via UseUrls method in IWebHostBuilder. I don't want to restart the entire web server in the process as I need to keep servicing any existing requests on other ports. Is this possible?

Upvotes: 5

Views: 494

Answers (1)

Caleb
Caleb

Reputation: 2267

I was able to add an endpoint programmatically by injecting IConfiguration and triggering a reload after adding an endpoint to the Kestrel section:

// IConfiguration comes from DI
public class KestrelReloader(IConfiguration config) {

    private async Task Reload()
    {
        const string apiUrl = "http://localhost:5001";
        var section = config.GetSection("Kestrel:EndPoints:HttpLocalhost:Url");
        section.Value = apiUrl;
        if (config is IConfigurationRoot configRoot)
        {
            configRoot.Reload();
        }
    }
}

Upvotes: 0

Related Questions