无法访问 ASP.net core 3.0 中的用户机密

Joh*_*ode 5 c# asp.net-core-mvc .net-core asp.net-core asp.net-core-3.0

我的问题很简单。我有一个 ASP.net core 3.0 应用程序,我使用 Visualstudio 添加了机密,并正常将我的机密粘贴到机密文件中。然后在我的 Program.cs 中,我添加了对 addusersecrets 的调用,如下所示:

...
...
.AddUserSecrets<Startup>()
Run Code Online (Sandbox Code Playgroud)

但是,当像Configuration["Authentication:Secret"]我以前在 appsettings.json 中那样调用我的秘密时,我得到一个 null 值作为返回。

我浏览了 stackoverflow 并尝试了解决方案,例如更改我的 addsecrets,如下所示:

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

//OR

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

Run Code Online (Sandbox Code Playgroud)

但这些都不起作用。

我想知道这个秘密的东西是否适用于 ASP.NET Core,因为我没有看到我的代码不起作用的任何原因。如果有人得到它,你能告诉我解决方案吗?谢谢。

小智 5

请务必检查您是否已将变量设置"ASPNETCORE_ENVIRONMENT""Development",否则您的应用程序将不会添加您的用户机密。

  • 在 powershell 中:

    $Env:ASPNETCORE_ENVIRONMENT = "开发"

  • 命令:

    setx ASPNETCORE_ENVIRONMENT“开发”


Ton*_*Ngo 4

你的代码是这样的吗?

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();
}
Run Code Online (Sandbox Code Playgroud)