C# – User secrets aren’t being loaded when you’re using GenerateAssemblyInfo=false

Problem

You’ve configured user secrets properly, but the framework will not swap in the secret value at runtime. It appears to not be loading secrets.json at all.

Check if you’re using GenerateAssemblyInfo=false in your .csproj file.

When you add a user secrets file, it generates a user secrets guid and puts it in your .csproj as the UserSecretsId property. It also puts this guid in an assembly info attribute called UserSecretsIdAttribute. If you have GenerateAssemblyInfo=false, it won’t add UserSecretsIdAttribute for you, which is why it won’t load the user secrets file at runtime.

If you’ve put GenerateAssemblyInfo=false in your .csproj file, your .csproj file may look something like this:

<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> </PropertyGroup> <PropertyGroup> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <UserSecretsId>b5dc3595-d335-49aa-b0a6-96e2f08e2206</UserSecretsId> </PropertyGroup> </Project>
Code language: HTML, XML (xml)

Solution

To use GenerateAssemblyInfo=false and user secrets at the same time, you’ll need to add UserSecretsIdAttribute in your project, like this:

using System; using System.Reflection; [assembly: Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute("b5dc3595-d335-49aa-b0a6-96e2f08e2206")]
Code language: C# (cs)

Note: You need to use the same guid that’s in the .csproj UserSecretsId property. In this example, it’s b5dc3595-d335-49aa-b0a6-96e2f08e2206.

If you don’t need to use GenerateAssemblyInfo=false, then remove it from your .csproj file.

Leave a Comment