在 .NET Core 2.1 控制台应用程序中配置用户机密

Gia*_*cca 2 c# console-application .net-core

我知道在 中.NET Core MVC,您可以使用上下文菜单执行此操作,但此选项不适用于.NET Core Console应用程序。

如何将用户机密添加到我的 .NET Core 2.1 控制台应用程序?

Gia*_*cca 5

添加<UserSecretsId>标签的.csproj file

<PropertyGroup>  
   <OutputType>Exe</OutputType>
   <TargetFramework>netcoreapp2.x</TargetFramework>
   <UserSecretsId>4245b512-chsf-9f08-09ii-12an1901134c</UserSecretsId>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

在解决方案文件夹(包含.csproj文件的文件夹)中打开一个命令提示符窗口,然后键入

dotnet user-secrets set SecretName SecretKey
Run Code Online (Sandbox Code Playgroud)

更换SecretNameSecretKey相应地。

然后您可以在您的应用程序中使用它访问它

class Program
{ 
    private static IConfigurationRoot Configuration;
    const string SecretName= "SecretName";

    private static void Main(string[] args)
    {
        BootstrapConfiguration();
        Console.WriteLine($"The Secret key is {Configuration[SecretName]}");
    }
}

private static void BootstrapConfiguration()
{
    string env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

    if (string.IsNullOrWhiteSpace(env))
    {
        env = "Development";
    }

    var builder = new ConfigurationBuilder();

    if (env == "Development")
    {
        builder.AddUserSecrets<Program>();
    }

    Configuration = builder.Build();
}
Run Code Online (Sandbox Code Playgroud)