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.

7
  • you don't have an startup.cs ? Commented Feb 27, 2020 at 18:46
  • @Mehrdad, this is inside a unit test project Commented Feb 27, 2020 at 18:47
  • 1
    Shouldn't that be "myKey" (the name of your key)? Commented Feb 27, 2020 at 18:55
  • In your code sample do you mean config["myKey"] or are you doing config["myValue"]? Commented Feb 27, 2020 at 18:56
  • @knittl Typo! Trust me, it's correct in the actual code. See edited OP. Commented Feb 27, 2020 at 18:57

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

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?
I wouldn't use SetBasePath and AddEnvironmentVariables unless they're really necessary, keeping it simple.
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.
could I also draw your attention to this quesion? :) stackoverflow.com/questions/60441040/…
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?
0

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.