Reputation: 3907
I was tring .NET core with a console application and I'm stucked on reading from appsettings.json
.
Here's my code:
{
"ConnectionStrings": {
"DataBaseConnectionString": "Server=xxxxxx"
}
}
...
var builder = new ConfigurationBuilder()
// .SetBasePath("")
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
configuration = builder.Build();
var xx = configuration.GetConnectionString("DataBaseConnectionString");
I got null on xx
, what am I doing wrong?
Thanks
Upvotes: 7
Views: 7005
Reputation: 25069
Your code is correct. Set optional: false
to check the file exists. The keypoint for a console app is to ensure appsettings.json
has Copy to output directory: Always
property.
Here is a minimal reproducible example:
//set "optional: false" to fail-fast without a file
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false);
var configuration = builder.Build();
//contains "Server=xxxxxx"
string str = configuration.GetConnectionString("DataBaseConnectionString");
Actual documentation: Configuration in ASP.NET Core
Upvotes: 8