Last active
March 18, 2024 09:27
-
-
Save Tratcher/ae23d9a7b4c8c7c37d7a769ad68bd228 to your computer and use it in GitHub Desktop.
Kestrel programmatic rebinding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This shows how to change Kestrel's bindings programmatically through the IConfiguraiton abstraction. | |
// TFM: .NET 5.0 | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.Hosting; | |
using System; | |
using System.Threading; | |
namespace WebApplication85 | |
{ | |
public class Program | |
{ | |
private static IConfigurationRoot KestrelConfig; | |
public static void Main(string[] args) | |
{ | |
var configBuilder = new ConfigurationBuilder(); | |
// A custom source/provider is required because the InMemory one doesn't support key removal. | |
configBuilder.Add(new MutableSource()); | |
KestrelConfig = configBuilder.Build(); | |
var timer = new Timer(_ => | |
{ | |
var port = new Random().Next(5000, 5005); | |
var key = $"Endpoints:{port}:Url"; | |
var url = KestrelConfig[key]; | |
if (string.IsNullOrEmpty(url)) | |
{ | |
url = $"https://*:" + port; | |
KestrelConfig[key] = url; | |
Console.WriteLine("Adding: " + url); | |
} | |
else | |
{ | |
KestrelConfig[key] = null; | |
Console.WriteLine("Removing: " + url); | |
} | |
Console.WriteLine(KestrelConfig.GetDebugView()); | |
KestrelConfig.Reload(); | |
}, null, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)); | |
CreateHostBuilder(args).Build().Run(); | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
webBuilder.UseStartup<Startup>(); | |
webBuilder.ConfigureKestrel(kOptions => | |
{ | |
// We need at least one binding to actually start the server. | |
// This could also be in config. | |
kOptions.ListenAnyIP(4999, listenOptions => | |
{ | |
listenOptions.UseHttps(); | |
}); | |
kOptions.ConfigureHttpsDefaults(httpsOptions => | |
{ | |
// Set up https for config based endpoints. Defaults to the dev certificate. | |
}); | |
kOptions.Configure(KestrelConfig, reloadOnChange: true); | |
}); | |
}); | |
private class MutableProvider : ConfigurationProvider | |
{ | |
public override void Set(string key, string value) | |
{ | |
if (value == null) | |
{ | |
Data.Remove(key); | |
} | |
else | |
{ | |
Data[key] = value; | |
} | |
} | |
} | |
private class MutableSource : IConfigurationSource | |
{ | |
public IConfigurationProvider Build(IConfigurationBuilder builder) | |
{ | |
return new MutableProvider(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment