简体   繁体   English

如何以编程方式添加用户机密?

[英]How to add User Secrets programmatically?

I would like to create User Secrets from a .NET Core Application without using the dotnet executable.我想在不使用dotnet可执行文件的情况下从 .NET Core 应用程序创建用户机密 Is there a standard way to do it?有没有标准的方法来做到这一点?

Just create secrets.json file where it should be and follow the guide you mentioned.只需在应有的位置创建 secrets.json 文件,然后按照您提到的指南进行操作。 File path (In my case directory UserSecrets did not exist, so I had to create it beforehand):文件路径(在我的例子中, UserSecrets目录不存在,所以我必须事先创建它):

%APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json

where <user_secrets_id> is GUID.其中<user_secrets_id>是 GUID。

File content:文件内容:

{
  "PW": "test"
}

Edit your .csproj file to include secrets id, replace GUID with your value编辑您的 .csproj 文件以包含机密 ID,将 GUID 替换为您的值

<UserSecretsId>da96d8db-5651-4925-b1e9-2fdbbea03e81</UserSecretsId>

And finally modify Startup.cs file to include your secrets最后修改 Startup.cs 文件以包含您的机密

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>(); // this line adds secrets to configuration
    }

    Configuration = builder.Build();

    var a = Configuration["PW"]; // value: test
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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