Use appsettings to drive environment specific settings such as UseUrls

99封情书 提交于 2019-12-05 07:46:06
Justin Saraceno

This is possible. Expanding on the answer given here, by creating the WebHostBuilder and ConfigurationBuilder in the Program.cs, it is possible to have access to the host environment and then configure the host URL and port in environment-specific appsettings files.

Assuming an appsettings.json and an apppsettings.Development.json file each with the following:

"hostUrl": "http://*:<port number here>"

Modify the Main with the following:

public static void Main(string[] args)
{
    var host = new WebHostBuilder();
    var env = host.GetSetting("environment");
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env}.json", optional: true)
        .AddEnvironmentVariables();
    var configuration = builder.Build();

    host.UseKestrel()
        .UseUrls(configuration["hostUrl"])
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .Build()
        .Run();
}

Using this code, the Startup.cs will still need to declare its own ConfigurationBuilder in order to publicly expose its Configuration property.

Or, starting from .NET Core 2.0, when creating the default IWebHostBuilder that will build the IWebHost implementation, you can use

return WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(configuration)
            .ConfigureAppConfiguration((builderContext, config) =>
            {
                // nb: here you may clear configuration(s) loaded so far
                var env = builderContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);
            })
            .UseStartup<Startup>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!