简体   繁体   中英

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.

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();
}

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

build.AddUserSecrets(Assembly.GetExecutingAssembly())

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"

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 指示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM