Reputation: 13945
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.
Upvotes: 7
Views: 15216
Reputation: 1
You have to write var myValue = config["AppSettings:myKey"];
instead of var myValue = config.GetSection("myKey");
, Because myKey
is inside of AppSettings:myKey
.
Upvotes: 0
Reputation: 4170
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"];
Upvotes: 7