gpt4 book ai didi

c# - 在 .NET Core 2.1 控制台应用程序中配置用户 secret

转载 作者:行者123 更新时间:2023-12-02 03:27:46 24 4
gpt4 key购买 nike

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

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

最佳答案

添加<UserSecretsId>标签 .csproj file .

<PropertyGroup>  
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.x</TargetFramework>
<UserSecretsId>4245b512-chsf-9f08-09ii-12an1901134c</UserSecretsId>
</PropertyGroup>

在解决方案文件夹(其中包含 .csproj 文件的文件夹)中打开命令提示符窗口并键入

dotnet user-secrets set SecretName SecretKey

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

关于c# - 在 .NET Core 2.1 控制台应用程序中配置用户 secret ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52732260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com