【问题标题】:Can't access User Secrets in ASP.net core 3.0无法访问 ASP.net core 3.0 中的用户机密
【发布时间】:2020-03-11 11:29:49
【问题描述】:

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

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

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

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

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

//OR

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

但是没有一个有效。

我想知道这个秘密的东西是否甚至可以在 asp.net 核心上运行,因为我看不出我的代码无法运行的任何原因。请如果有人得到它,你能告诉我一个解决方案吗? 谢谢。

【问题讨论】:

    标签: c# asp.net-core .net-core asp.net-core-mvc asp.net-core-3.0


    【解决方案1】:

    你的代码是这样的吗?

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

    【讨论】:

    • 是的。与此类似。
    • 你能告诉我你是如何在你的c#代码中读取你的配置文件的吗
    • 嗨,我在 Program.cs 中进行构建,但它看起来像这样:var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true) .AddEnvironmentVariables() .AddUserSecrets&lt;Startup&gt;(true, reloadOnChange: true) .Build();
    • 谢谢,你让我意识到我正在以不同的方式运行我的配置,将我的配置添加到 startup.cs 并在那里调用用户机密对我有帮助。
    【解决方案2】:

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

    • 在PowerShell中:

      $Env:ASPNETCORE_ENVIRONMENT = "开发"

    • 命令:

      setx ASPNETCORE_ENVIRONMENT "开发"

    【讨论】:

    • 对于生产环境中的应用程序来说,这种方法会说什么?
    • @David -- 我知道你的问题很老,但你不在生产环境中使用“用户机密”/secrets.json。严格来说是为了当地的发展。您可能希望使用 Azure Key Vault 或 Azure App Configuration 来存储生产机密、密钥、连接字符串等。
    【解决方案3】:

    用户机密现在存储在 csproj 项目文件中。这就是你可以阅读它的方式(见图)。我正在使用 asp.net 核心 5

    【讨论】:

    • 我需要访问不包含 Startup.cs 的项目的用户机密。
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    相关资源
    最近更新 更多