Search code examples
c#configurationappsettings.net-core-3.1

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


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.


Solution

  • .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.