Home > Net >  Use appsettings.custom.json to overwrite appsettings.json
Use appsettings.custom.json to overwrite appsettings.json

Time:10-27

I have an ASP.NET Core API that reads in config from a appsettings.json file. This is ran as a Windows service and can be installed/uninstalled. This means that updating will overwrite the appsettings.json file. To solve this, I want to be able to create a appsettings.custom.json, that contains only the settings from appsettings.json that I want a different value for. So basically this appsettings.custom.json file should overrule the settings from appsettings.json. I've been playing around, but the settings that are used are always from appsettings.json, it basically ignores the appsettings.custom.json.


        private const string CustomAppSettingsJson = "appsettings.custom.json";
        private const string DefaultAppSettingsJson = "appsettings.json";

 Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(DefaultAppSettingsJson, optional: false, reloadOnChange: true)
                .AddJsonFile(CustomAppSettingsJson, optional: true, reloadOnChange: true)
                .Build();

Is something like this possible? Can I make some sort of hierarchic order in the files?

I tried switching the order of the adding of the json files, but without success.

CodePudding user response:

The highest provider takes precedence so you'll need to swap the ordering.

var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(CustomAppSettingsJson, optional: true, reloadOnChange: true)
                .AddJsonFile(DefaultAppSettingsJson, optional: false, reloadOnChange: true)
                .Build()

https://youtu.be/sBQlIcdLM0s

CodePudding user response:

The issue was that the files were not added to the configuration used in startup that registers the options classes.

  • Related