0

I have a .NET Core 6 app, and I need it to load a setting from appsettings.json in the run folder.

The code to load the option is:

var sections = new ConfigurationBuilder().AddJsonFile( "C:\\DTS_API_8\\HereIntegrationSystemTest.NetCore\\bin\\Debug\\net6.0\\appsettings.json" ).Build().GetSection( "AppSettings" );
string serverURL = sections[ "DTS_url" ];
string serverURL2 = new ConfigurationBuilder().AddJsonFile( "appsettings.json" ).Build().GetSection( "AppSettings" ).GetValue<string>( "DTS_url" );
afterLoad = true;
      

The appsettings.json file is like:

{
  "AppSettings": {
    "DTS_url": "https://localhost:44353"        
  },
  ...
}

At line "afterLoad = true", the variable serverURL always contains the value https://localhost:44353 (which is correct).

But serverURL2 only has the value every second run, alternating between null and https://localhost:44353.

The above alternating behavior we see when appsettings.json file is marked as "Always copy" to execution folder. If appsettings.json is marked as "Copy if newer", then serverURL2 is always null at afterLoad = true;

Looking in the execution bin folder, the appsettings.json file is always the same and always has the setting "DTS_url". How can this be? I need it to always load the option without hardcoding the whole path to appsettings.json.

2
  • 1
    You've been talking about appConfig.json the whole time - I assume you really meant appsettings.json and thus I changed all mention of appconfig.json to appsettings.json .... Commented Jun 4, 2024 at 13:20
  • The code is broken, making me wonder what else is. Instead of using one ConfigurationBuilder and adding all the settings files to it, it uses one ConfigurationBuilder to read from a relative path, another to read from an unrelated absolute path that only exists during debugging. It's unclear what the missing settings file is supposed to be, but the one in bin/debug is deleted on every build. The other config builder is loading a local file which, in case of release builds, won't be the same one copied to bin/Debug Commented Jun 13, 2024 at 13:57

0

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.