Configuring DotNET Apps with Environment Variables
Effortlessly configure apps in DotNET Core with prefixed environment variables. Set and override appsettings.json values without code commits.
DotNET core is one of the most popular and powerful development frameworks. It is a large and well designed project but one common misunderstanding is the ways in which to configure an application using environment variables. Let us see the easier way to do so.
Store your settings in appsettings.json
First step is to define settings you wish to use in your projects appsettings.json
file. Here is an example:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AppConfig": {
"SqsQueueUrl": "todo-queue",
"TwilioSecret": "todo-secret"
}
}
Here we have the standard logging and allowed host properties found in most apps. We also added a custom field called AppConfig. Within our custom property there are two nested fields. If we want to use secret or sensitive data in these fields it is best not to commit them to code by writing them into appsettings. Instead we should build our application and pass the secrets as environment variables to override the appsettings config properties.
Make sure you enable env
In your Program.cs
make sure to enable environment variables with the WebApplication builder config.
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddEnvironmentVariables();
Setting environment variable overrides.
To replace values in your appsettings your must follow these rules:
- Prefix your env var with
ASPNETCORE_
- Use double underscore to separate nested fields
__
So to set the TwilioSecret in our AppConfig section we would run or build the application with the variable:
ASPNETCORE_AppConfig__TwilioSecret=my-secret