7

What I'm trying to do should be simple but I can not get it to work!!

My appsettings.json file:

{
  "AppSettings": {
    "myKey": "myValue",
  }
}

And then:

var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var myValue = config["myKey"];

myValue is null.

I also tried:

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables();
IConfiguration config = builder.Build();

var myValue = config.GetSection("myKey");

But again, myValue is null.

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193

2 Answers2

7

In your appsettings.json myKey is inside an AppSettings object.

That whole object is being loaded, so you'll need to reference it:

var myValue = config["AppSettings:myKey"];

Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#hierarchical-configuration-data

Gabriel Cappelli
  • 3,632
  • 1
  • 17
  • 31
  • Nailed it! Thank you!! Wow... spent hours on this. Much appreciated. Followup question: of the two examples/attempts I have above, which is better, and why? – Casey Crookston Feb 27 '20 at 19:08
  • 1
    I wouldn't use `SetBasePath` and `AddEnvironmentVariables` unless they're really necessary, keeping it simple. – Gabriel Cappelli Feb 27 '20 at 19:12
  • 1
    using `optional: false` sounds like a good idea, you wouldn't want your tests to run without the proper config values, since they'll probably fail anyway. – Gabriel Cappelli Feb 27 '20 at 19:13
  • could I also draw your attention to this quesion? :) https://stackoverflow.com/questions/60441040/deserialize-appsettings-json-in-unit-test – Casey Crookston Feb 27 '20 at 20:18
  • Suppose in the dev json file I created key called `key1` and in prod json file I create key called `key2`, then when I run the project in visual studio, it is reading both the keys. Shouldn't it read only the key from the dev json file? – variable Jan 12 '22 at 10:37
0

You have to write var myValue = config["AppSettings:myKey"]; instead of var myValue = config.GetSection("myKey");, Because myKey is inside of AppSettings:myKey.

Shunya
  • 2,344
  • 4
  • 16
  • 28
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 04 '22 at 09:10