Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables from appsettings.json for .net core console app?

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"
}
like image 265
Benny Avatar asked Nov 03 '19 23:11

Benny


People also ask

How do I add Appsettings json in .NET Core console app?

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.

How Appsettings json works in .NET Core?

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.


1 Answers

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.

like image 63
Simply Ged Avatar answered Oct 17 '22 06:10

Simply Ged