在 Visual Studio for Mac 中管理用户机密
1 问题描述
我们知道,在 Visual Studio 2019 中,右击项目可以直接管理用户机密,但在 Visual Studio for Mac 或 Visual Studio Code 中并没有该功能,那该怎么办呢?其实微软 .Net Core 已经为我们提供了相关的机密管理命令行工具。
2 解决办法
2.1 启用 secret 存储
dotnet user-secrets init
该命令将在项目文件 .csproj
中的 PropertyGroup
节点下添加 UserSecretsId
属性。
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>575b1a56-a746-45f7-91ce-561873619af8</UserSecretsId>
</PropertyGroup>
2.2 设置 secret
dotnet user-secrets set "MyKey" "888"
该命令用于设置 secrets.json
文件中的配置信息,如果是第一次设置将会创建该文件。
{
"MyKey": "888"
}
该文件在不同的操作系统下,存储的路径并不相同。
Windows
%APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.json
Mac 或 Linux
~/.microsoft/usersecrets/<userSecretsId>/secrets.json
注意:执行 set
命令前需要确保项目文件 .csproj
中有 UserSecretsId
属性(先执行 init
命令),否则会报以下错误:
Could not find the global property 'UserSecretsId' in MSBuild project 'xxx.csproj'. Ensure this property is set in the project or use the '--id' command line option.