I have developed a console application using .NET 6 and I am trying to get the connectionstring from my Appsettings.json but keep getting a null value.
My appsettings.json looks like:
{
"ConnectionStrings": {
"MyConnectionString": "Data Source=..."
}
}
For my Program.cs, I have tried different syntaxes from here and here
static void Main()
{
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfiguration _configuration = configurationBuilder.Build();
Console.WriteLine(_configuration["ConnectionStrings:MyConnectionString"]);
Console.WriteLine(_configuration.GetConnectionString("MyConnectionString"));
var services = new ServiceCollection();
services.AddDbContext<...>
}
But in my console, it returns null value. What should be the correct syntax?
################# EDIT ########################
I had to change the property of the appsettings.json file from "Do not copy" to "copy if newer" in the output directory. It works now.