Asp.net core, system environment variables

I started working on a new small project. I took some time in reading about my option on storing environment variables. (For like the 10th time..)
I am using AWS’s Secrets Manager for my NanisuruApp, but this time around I decided to simply utilize the System Environment Variables on Windows.

Steps taken (Asp.net Core 6.x+)
1.) Added my custom prefix to use.
builder.Configuration.AddEnvironmentVariables(prefix: “CustomPrefix_”);

example environtment variable:
CustomPrefix_DevConnectionString = value

2.) Created 2 profile in launchSettings.json for a “Development” and “Production” profile.
“ASPNETCORE_ENVIRONMENT”: “Production” and copy and paste for Development

3.) Create a cooresponding appsettings file for both Development and Production.
appsettings.Development.json
appsettings.Production.json

something like this (appsettings.Development.Json)

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "DevConnectionString": "connection"
}

4.) Then I did a sloppy job at loading different connection info based on the project’s environment.

(Program.cs)

// Enable custom environment variables.
builder.Configuration.AddEnvironmentVariables(prefix: "CustomPrefix_");

// Store database connection string
string? connectionString = null;

// Create environment variable to check dev/prod/staging status
IHostEnvironment currentEnvironment = builder.Environment;

// Load different database connection string depending on dev or prod environment
if (currentEnvironment.IsDevelopment())
{
    connectionString = builder.Configuration.GetValue<string>("DevConnectionString");
}
else if (currentEnvironment.IsProduction())
{
    connectionString = builder.Configuration.GetValue<string>("ProdConnectionString");
}

Something important. After adding/editing system environment variables, make sure to restart Visual Studio. These variables are only loaded during launch of the editor.

Leave a Reply

Your email address will not be published. Required fields are marked *