First of all my main purpose is to setup the IP and Port for my application dynamically.
I'm using IConfiguration
to inject a json config file, like some tutorial mentioned.
However, I can't retrieve the configuration in Program.cs, because my WebHostBuilder
will use the StartUp and Url at the same time.
So at the time the host build up, there is nothing in my configuration.
WebProtocolSettings settings_Web = new WebProtocolSettings();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls(settings_Web.Url + ":" + settings_Web.Port)
.Build();
In Startup.cs
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
// Adds services required for using options.
services.AddOptions();
var _WebProtocolSettings = Configuration.GetSection("WebProtocolSettings");
// Register the IConfiguration instance
services.Configure<WebProtocolSettings>(_WebProtocolSettings);
}
My appsettings.json:
{
"WebProtocolSettings": {
"Url": "127.0.0.1",
"Port": 5050
}
}
My WebProtocolSettings.cs:
public class WebProtocolSettings
{
public string Url { get; set; }
public int Port { get; set; }
}