.NET Core console application, how to configure appSettings per environment?

后端 未结 7 953
囚心锁ツ
囚心锁ツ 2020-12-04 14:15

I have a .NET Core 1.0.0 console application and two environments. I need to be able to use appSettings.dev.json and appSettings.test.json based on

相关标签:
7条回答
  • 2020-12-04 14:44

    For those who are using .NET Core version 2.1.0+ and Microsoft.Extensions.Hosting to host your console app, you can use the following code (according to the Feiyu Zhou's answer in another thread):

    var hostBuilder = new HostBuilder()
        .ConfigureHostConfiguration(config =>
        {
            if (args != null)
            {
                // enviroment from command line
                // e.g.: dotnet run --environment "Staging"
                config.AddCommandLine(args);
            }
        })
        .ConfigureAppConfiguration((context, builder) =>
        {
            builder.SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false)
                .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true);
        })
    
    0 讨论(0)
提交回复
热议问题