In a simple static files ASP.NET Core 3.1 web server that always listens on http://localhost, I would like to configure the port and the webroot using IConfiguration
and a custom configuration section. Unfortunately there doesn't seem to be a way to get the IConfiguration
instance in ConfigureWebHostDefaults
.
How can I get access to the regular IConfiguration
in a place where I can also call UseUrls
and UseWebRoot
?
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
webBuilder =>
{
// Where do I get configuration from in the following two lines?
webBuilder.UseWebRoot(configuration.GetValue<string>("MySection:webroot"));
webBuilder.UseUrls($"http://localhost:{configuration.GetValue<int>("MySection:port")}");
webBuilder.UseStartup<Startup>();
});
}
public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
}
}
As described here the only thing which should be done is to build a configuration in your main method. See a code which uses appsettings.json to declare a path to my root folder.