7

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

1
  • If someone is also getting System.InvalidOperationException: The ConnectionString property has not been initialized error do this: right click on appsettings.json -> Properties -> Set Copy to output directory to Copy always Commented Mar 27, 2023 at 19:39

1 Answer 1

8

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

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

Comments

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.