Using secrets in your appsettings.json via Visual Studio 2022 and dotnet CLI

You’ve got yourself an appsettings.json file for your ASP.NET core application and you’re using sensitive data, such as passwords or other secrets. Now you obviously don’t want to commit those secrets to source control, so you’re not going to want to store these values in your appsettings.json file.

There’s several ways to achieve this, one of those is to use Visual Studio 2022 “Manage User Secrets” option which is on the context menu off of your project file. There’s also the ability to use to dotnet CLI for this as we’ll see later.

This context menu option will create a secrets.json in %APPDATA%\Microsoft\UserSecrets\{Guid}. The GUID is stored within your .csproj in a PropertyGroup like this

<UserSecretsId>0e6abf63-deda-47fc-9a80-1cb56abaeead</UserSecretsId>

So the secrets file can be used like this

{
  "ConnectionStrings:DefaultConnection": "my-secret"
}

and this will map to your appsettings.json, that might look like this

{
  "ConnectionStrings": {
    "DefaultConnection": "not set"
  },
}

Now we can access the configuration in the usual way, for example

builder.Configuration.AddUserSecrets<Program>();

var app = builder.Build();
var connectionString = app.Configuration.GetSection("ConnectionStrings:DefaultConnection");
var defaultConnection = connectionString.Value;

When somebody else clones your repository you’ll need to recreate the secrets file, we could use _dotnet user-secrets_ for example

dotnet user-secrets set "ConnectionStrings:DefaultConnection" "YourConnectionString"

and you can list the secrets using

dotnet user-secrets list