'Can't access User Secrets in ASP.net core 3.0

My question is simple. I have an ASP.net core 3.0 app, I added secrets using visualstudio and pasted my secrets into the secret file normally. Then inside my Program.cs, I added a call to addusersecrets as follows:

...
...
.AddUserSecrets<Startup>()

But while calling my secrets like Configuration["Authentication:Secret"] as I used to do when it was in appsettings.json, I get a null value in return.

I went through stackoverflow and tried solutions like changing my addsecrets as follows:

.AddUserSecrets("fds...-...-...askd")

//OR

.AddUserSecrets(typeof(Startup).Assembly, true, reloadOnChange: true)

BUt none of then works.

I wonder if this secret stuff even works on asp.net core, because I don't see any reason my code doesn't work. please if someone gets it, can you tell me a solution ? Thanks.



Solution 1:[1]

Did your code look like this ?

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", 
                     optional: false, 
                     reloadOnChange: true)
        .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        builder.AddUserSecrets<Startup>();
    }

    Configuration = builder.Build();
}

Solution 2:[2]

Be sure to check that you've set the "ASPNETCORE_ENVIRONMENT" variable to "Development", else your app wont add your user secrets.

  • in powershell:

    $Env:ASPNETCORE_ENVIRONMENT = "Development"

  • cmd:

    setx ASPNETCORE_ENVIRONMENT "Development"

Solution 3:[3]

For .Net 6 that doesn't use Startup one loads the assembly such as

build.AddUserSecrets(Assembly.GetExecutingAssembly())

Solution 4:[4]

User secrets are stored now in csproj project file. This is how you can read it(see image). I am using asp.net core 5 instructions

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tony Ngo
Solution 2 Iskuskov Alexander
Solution 3 ΩmegaMan
Solution 4 Talley Ouro