How to merge appsettings.json depending on the selected build configuration in Net Core 3.1?
Asked Answered
A

1

7

I have a Worker Service in Net Core 3.1 that reads Production settings from the appsettings.json file and, during development (using the "Debug" build configuration), overwrites appsettings.json settings with appsettings.Development.json, as expected.

I created a build configuration and publish configuration for our QA environment and I want that the appsettings.QA.json file to be merged with appsettings.json at build / publish time. But publishing the project only copies appsettings.json with the production settings without merging with the settings in the aspsetting.QA.json file.

How can I achieve this? I didn't want to copy appsettings.QA.json to the QA environment and set DOTNET_ENVIRONMENT to QA. I would like not to depend on environment variables in this case.

Aviation answered 18/6, 2020 at 15:15 Comment(0)
J
7

.Net Core does not merge the files into a physical file. They get merged in memory using such block of code in your Program.cs.

            Host.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((hostingContext, config) =>
             {
                 var env = hostingContext.HostingEnvironment;
                 config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                 
                 config.AddEnvironmentVariables();
             })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

All you need to do is to set the environment variable ASPNETCORE_ENVIRONMENT and .net core will automatically take care of it.

Jettiejettison answered 2/3, 2021 at 7:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.