我知道在 .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
替换SecretName
和SecretKey
相应地。
然后您可以使用以下方式在应用程序中访问它
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/