当我创建一个新的ASP Web-Application,.NET时,我可以在Visual中右键单击该项目,并看到一个名为“”的上下文菜单条目。
当我创建一个新的Console-Application,.NET时,我看不到这个上下文菜单条目。
但是,"Web"-Application在项目设置中显示为“控制台”应用程序。有什么方法可以在控制台应用程序中获得这个上下文菜单条目吗?
发布于 2018-02-07 14:40:38
右击的“管理用户机密”只能在web项目中使用。
控制台应用程序的进程略有不同。
它需要在csproj文件中手动输入所需的元素,然后通过PMC添加秘密。
在这篇博文中,我一步一步地概述了在我目前的项目中为我工作的过程:
tl;dr
步骤1
右键单击“项目”并单击“编辑projectName.csproj”
步骤2
将<UserSecretsId>Insert New Guid Here</UserSecretsId>添加到TargetFramework下的csproj
在csproj中的项组中添加<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0"/>
步骤3
将PowerShell (admin) cd打开到项目目录中,
输入dotnet user-secrets set YourSecretName "YourSecretContent"
这将在以下文件中创建一个secrets.json文件:
%APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.json其中userSecretsId =为csproj创建的新Guid
步骤4
打开secrets.json并进行编辑,使其看起来类似于
{
"YourClassName":{
"Secret1":"Secret1 Content",
"Secret2":"Secret2 Content"
}
} 通过添加类的名称,您可以将机密绑定到要使用的对象。
创建一个基本POCO,其名称与您刚才在JSON中使用的名称相同。
namespace YourNamespace
{
public class YourClassName
{
public string Secret1 { get; set; }
public string Secret2 { get; set; }
}
}步骤5
向项目中添加Microsoft.Extensions.Configuration.UserSecrets Nuget包
添加
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddUserSecrets<YourClassName>()
.AddEnvironmentVariables();&
var services = new ServiceCollection()
.Configure<YourClassName>(Configuration.GetSection(nameof(YourClassName)))
.AddOptions()
.BuildServiceProvider();
services.GetService<SecretConsumer>();到您的Program.cs文件。
然后将IOptions<YourClassName>注入到类的构造函数中。
private readonly YourClassName _secrets;
public SecretConsumer(IOptions<YourClassName> secrets)
{
_secrets = secrets.Value;
}然后使用_secrets.Secret1;访问机密
感谢Patric指出services.GetService<NameOfClass>();应该是services.GetService<SecretConsumer>();
发布于 2019-06-13 20:29:13
Manage User Secrets可以从VisualStudio2019(在16.1.3版本中验证)以来的.NET核心控制台项目(不仅仅是ASP.NET Core )的上下文菜单中获得,只要您引用了Microsoft.Extensions.Configuration.UserSecrets NuGet。
发布于 2020-07-18 19:06:07
DotNetCore3.1--在我只需要隐藏密码的情况下找到的最简单的方法。
使用项目文件夹中的命令行创建用户机密
dotnet user-secrets init
dotnet user-secrets set mailpassword password1在Program.cs中
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
var secretProvider = config.Providers.First();
secretProvider.TryGet("mailpassword", out var secretPass);
//'secretPass' should now contain the password
//if the "mailpassword" secret is not found, then 'secretPass' will be null如果您对配置做了更多的事情,您可能需要调整.First()
https://stackoverflow.com/questions/42268265
复制相似问题