msh*_*hwf 0 .net-core asp.net-core asp.net-core-2.1
JSON 文件和 ASP.NET Core 中的配置之间的关系令人沮丧。我设定了一个这样的秘密:
dotnet user-secrets set "Pwd" "123"
Run Code Online (Sandbox Code Playgroud)
似乎没有办法通过IConfiguration.GetSection方法检索它,只能IConfiguration.GetValue使用,我需要使用IConfiguration.GetSectionPOCO 对象绑定该值:
public class AppSecrets
{
public int Pwd { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后我添加了另一个秘密:"parent:pwd" "456"
查看自动生成的 JSON 文件,它看起来像一个带有两个密钥的常规 JSON:
{
"Pwd": "123",
"parent:pwd": "456"
}
Run Code Online (Sandbox Code Playgroud)
那么是什么让冒号对于 .NET Core 中的配置有特殊意义呢?他们在文档中 提到:
在前面的示例中,冒号表示 Movies 是具有 ServiceApiKey 属性的对象文字。
parent但在我的示例中,尽管未按名称映射到 AppSecrets 类,但仍检索到了该值。
还有一点让我感到沮丧的是,值传递给项目属性中的应用程序参数的方式,如下所示:
--user:data:year 1991
Run Code Online (Sandbox Code Playgroud)
我们可以传递更多层次节点吗?
很抱歉我的沮丧让你感到沮丧。我刚刚发现 .NET 核心!
考虑一个用于 smtp 设置的 poco 类:
public class SmtpOptions
{
public string Server { get; set; }
public int Port { get; set; } = 25;
public string User { get; set; }
public string Password { get; set; }
public string DefaultEmailFromAddress { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您可以将其放入 appsettings.json 中,如下所示:
{
"SmtpOptions": {
"Server": "MyServer",
"Port": "25",
"User": "MyUser",
"Password": "MyPassword",
"DefaultEmailFromAddress": "noreply@mydomain"
}
}
Run Code Online (Sandbox Code Playgroud)
像这样注册一下,现在 poco 就可以注入到任何地方了。
services.Configure<SmtpOptions>(configuration.GetSection("SmtpOptions"));
Run Code Online (Sandbox Code Playgroud)
如果你想在用户机密中做到这一点,你需要多个命令和冒号语法,如下所示:
dotnet user-secrets set "SmtpOptions:Server" "MyServer"
dotnet user-secrets set "SmtpOptions:Port" "25"
dotnet user-secrets set "SmtpOptions:User" "MyUser"
dotnet user-secrets set "SmtpOptions:Password" "MyPassword"
dotnet user-secrets set "SmtpOptions:DefaultEmailFromAddress" "noreply@mydomain"
Run Code Online (Sandbox Code Playgroud)
冒号以命令行中可能的方式表达层次结构,以便该语法可用于设置用户机密或环境变量,从而创建与 json 相同的层次结构。
| 归档时间: |
|
| 查看次数: |
2509 次 |
| 最近记录: |