I'm working with a C# class that reads from appsettings using
Environment.GetEnvironmentVariable("setting")
I want to make another console program (.net core 3.0) that reads settings from appsettings.json and loads them into environment variables.
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
IConfiguration config = builder
.Build();
var businessLogic = new BusinessLogic(); // uses GetEnvironmentVariable to get configuration
}
In my business logic class, the environment variables aren't getting pulled back correctly. What might be the problem?
appsettings.json is in this format:
{
"SETTING" : "setting value"
}
Add Json File After adding the file, right click on appsettings. json and select properties. Then set “Copy to Ouptut Directory” option to Copy Always. Add few settings to json file, so that you can verify that those settings are loaded.
json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information. Actually, in ASP.NET Core, the application configuration settings can be stored in different configurations sources such as appsettings.
Environment.GetEnvironmentVariable("setting")
will always try to read the data from an environment variable, not from your loaded config.
You need to change your BusinessLogic
class to accept the config
object you built and use that to access the settings. An example:
public class BusinessLogic
{
public BusinessLogic(IConfiguration config)
{
var value = config.GetValue<string>("SETTING");
}
}
In this example value
will contain the correct value of SETTING
if it was last set in appsettings.json
or using an environment variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With