0

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.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Sylvain C.
  • 1,043
  • 1
  • 11
  • 27
  • 2
    In the IDE right click on the `appsettings.json` file and verify that it has _"Copy to output directory"_ is set to `Copy if newer` (Also setting _"Build Action"_ to `Content` can be useful). – Guru Stron Apr 06 '23 at 19:31

0 Answers0