DotNet Configuration Part 1
In this first part of the series I will show you an approach I have used successfully in managing configurations and secrets when building .net core apps
Spin up Visual studio and create a .net 6 core console app.
Add some appsettings.json file for environment specific variables
Then add an Item group to the project file and paste the following to nest the appsettings files
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Update="appsettings.Local.json">
<DependentUpon>appsettings.json</DependentUpon>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="appsettings.Docker.json">
<DependentUpon>appsettings.json</DependentUpon>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
Add the following variable to each of the files
appsettings.json -> "DemoUsername": "DefaultUserName"
appsettings.Docker.json -> "DemoUsername": "DockerUserName"
appsettings.Local.json -> "DemoUsername": "LocalUserName"
Open the properties of the project and navigate to Debug -> General -> Open debug launch profiles UI.
Add the following Environment Variable
DOTNET_ENVIRONMENT = Local
Close that UI and you should now have a properties folder with the launchSettings.json added.
Install the following Nuget packages
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.UserSecrets
- Microsoft.Extensions.Hosting
Then Select the project -> Manage User Secrets
This should open the secrets.json file that is unique to you. Add a variable to this file
{
"SecretPassword": "HelloFromUserSecrets"
}
Paste the following code into the program.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Reflection;
using IHost host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var settings = config.Build();
var environmentName = context.HostingEnvironment.EnvironmentName;
var isLocalEnv = environmentName == "Local" || environmentName == "Docker";
if (isLocalEnv)
{
config.AddUserSecrets(Assembly.GetExecutingAssembly(), true);
}
else
{
//ToDo Add AZ App Configuraton
}
})
.Build();
var config = host.Services.GetService<IConfiguration>();
Console.WriteLine("Username is - " + config.GetValue<string>("DemoUsername"));
Console.WriteLine("Password is - " + config.GetValue<string>("SecretPassword"));
Press F5 to run the project and you should see the variables printed out in the console window.