UseWebRoot and UseUrls from IConfiguration

727 views Asked by At

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();
    }
}
1

There are 1 answers

3
Ondřej Mach On

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.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    var configuration = new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddEnvironmentVariables()
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddCommandLine(args)
                        .Build();

                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseIISIntegration();
                    webBuilder.UseKestrel();
                    webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
                    webBuilder.UseWebRoot(configuration["UnifiWebRoot:Path"]);
                    webBuilder.UseUrls("https://localhost:5000");
                });