User Secrets not working due to missing UserSecretsIdAttribute

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 – add UserSecretsIdAttribute

If you want to use GenerateAssemblyInfo=false and user secrets, you have to add UserSecretsIdAttribute yourself. Here’s an example of how to add 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.

5 thoughts on “User Secrets not working due to missing UserSecretsIdAttribute”

Leave a Reply to Anonymous Cancel reply