14

I have the following setup in my Startup:

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", true, true);
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true)

appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
}

I know I can override the effective settings for a given environment by adding a matching JSON structure with different values and omitting those I want to inherit, e.g. appsettings.Development.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
}

But can I remove an entry or a section except by overriding each value property with an empty value?

-S

Sigurd Garshol
  • 1,376
  • 3
  • 15
  • 36

1 Answers1

9

According to Configuration in ASP.NET Core documentation, settings are loaded from both files and if a setting is specified in both on them, than the one in the latter, i.e. appsettings.{env.EnvironmentName}.json in your setup, will override the first one.

So, if a setting is specified in the appsettings.json file and you want to remove it when running in the Development environment, you will need to explicitly set that accordingly ("", {}, etc. depending on the setting) in the appsettings.Development.json file.

However, such setup may suggest your setting should not lie in the generic appsettings.json file, but in the specific environments configuration settings file directly. This way, it might be easier to write your settings.

smn.tino
  • 2,272
  • 4
  • 32
  • 41
  • 1
    It's not legal to assign `null` (as per https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1&tabs=basicconfiguration#values) – David Gardiner Feb 07 '20 at 05:51
  • @DavidGardiner you are right. I just updated based on your feedback, thanks. – smn.tino Feb 07 '20 at 09:47
  • 2
    This answer does not really provide definitive solution. For example, if one of my config keys is a TimeSpan, and I configure some value for it in `appsettings.json`, how can I unset it in `appsettings.Development.json`? If I set it to `"configKey": ""`, I will get an exception, because an empty string is not assignable to a `TimeSpan`. – mnj Jul 18 '22 at 08:16