英文:
How can I read an object tree using Configuration GetRequiredSection()?
问题
如何读取具有嵌套属性的.NET Core配置部分?
这是我的配置(摘录):
{
"SMTP":
{
"Name": "...",
"UserName": "...",
"Password": "...",
"HostName": "...",
"Port": "587",
"Security": "STARTTLS",
"OAuth2":
{
"ClientId": "",
"ClientSecret": "",
"Scopes":
[
]
}
}
}
这是我用来读取上述配置部分的record
类型:
public record OAuth2Credentials(string ClientId, string ClientSecret, string[] Scopes);
public record SmtpConfiguration(string Name, string UserName, string Password, string HostName, int Port, string Security, OAuth2Credentials OAuth2);
然后,当我尝试使用以下代码行读取上述配置时:
SmtpConfiguration smtpConfig =
Program.Configuration!
.GetRequiredSection("SMTP")
.Get<SmtpConfiguration>()!;
...我得到以下错误:
System.InvalidOperationException: Cannot create instance of type
'WebApi.SendEMail.SmtpConfiguration' because parameter 'OAuth2' has
no matching config. Each parameter in the constructor that does not
have a default value must have a corresponding config entry.
.
如何使用Configuration的GetRequiredSection()方法读取对象树?
编辑
我从给出的答案中选择的解决方案:
using System;
public record OAuth2Credentials(string ClientId, string ClientSecret)
{
public string[] Scopes = Array.Empty<string>();
}
public record SmtpConfiguration(string Name, string UserName, string Password, string HostName, int Port, string Security)
{
public OAuth2Credentials OAuth2 = new OAuth2Credentials("", "");
}
try
{
smtpConfig = Program.Configuration!.GetRequiredSection("SMTP").Get<SmtpConfiguration>()!;
smtpConfig.OAuth2 = Program.Configuration!.GetRequiredSection("SMTP:OAuth2").Get<OAuth2Credentials>()!;
smtpConfig.OAuth2.Scopes = Program.Configuration!.GetRequiredSection("SMTP:OAuth2:Scopes").Get<string[]>()!;
}
catch (InvalidOperationException ex) { return TypedResults.BadRequest($"Invalid SMTP configuration: {ex.Message}"); }
这个解决方案对我来说似乎是最类型安全的。
英文:
How can I read a .NET Core configuration section having nested properties?
This is my configuration (excerpt):
{
"SMTP":
{
"Name": "...",
"UserName": "...",
"Password": "...",
"HostName": "...",
"Port": "587",
"Security": "STARTTLS",
"OAuth2":
{
"ClientId": "",
"ClientSecret": "",
"Scopes":
[
]
}
}
}
And these are the record
types I'm using to read above configuration section:
public record OAuth2Credentials(string ClientId, string ClientSecret, string[] Scopes);
public record SmtpConfiguration(string Name, string UserName, string Password, string HostName, int Port, string Security, OAuth2Credentials OAuth2);
Then, when I try to read above configuration using the following line:
SmtpConfiguration smtpConfig =
Program.Configuration!
.GetRequiredSection("SMTP")
.Get<SmtpConfiguration>()!;
… I get the following error:
System.InvalidOperationException: Cannot create instance of type
'WebApi.SendEMail.SmtpConfiguration' because parameter 'OAuth2' has
no matching config. Each parameter in the constructor that does not
have a default value must have a corresponding config entry.
.
How can I read an object tree using Configuration GetRequiredSection()?
Edit
My Solution Chosen From Given Answers:
using System;
public record OAuth2Credentials(string ClientId, string ClientSecret)
{
public string[] Scopes = Array.Empty<string>();
}
public record SmtpConfiguration(string Name, string UserName, string Password, string HostName, int Port, string Security)
{
public OAuth2Credentials OAuth2 = new OAuth2Credentials("", "");
}
try
{
smtpConfig = Program.Configuration!.GetRequiredSection("SMTP").Get<SmtpConfiguration>()!;
smtpConfig.OAuth2 = Program.Configuration!.GetRequiredSection("SMTP:OAuth2").Get<OAuth2Credentials>()!;
smtpConfig.OAuth2.Scopes = Program.Configuration!.GetRequiredSection("SMTP:OAuth2:Scopes").Get<string[]>()!;
}
catch (InvalidOperationException ex) { return TypedResults.BadRequest($"Invalid SMTP configuration: {ex.Message}"); }
This solution seems most type-safe to me.
答案1
得分: 2
因为你正在使用record,所以你必须为每个参数提供一个默认值,以便像这样使用它。
下面的代码是使用示例的完整示例:
public record SmtpConfiguration(string Name, string UserName, string Password, string HostName, int Port, string Security, OAuth2Credentials OAuth2);
public record OAuth2Credentials(string ClientId, string ClientSecret, string[] Scopes);
SmtpConfiguration smtpConfig = new SmtpConfiguration("", "", "", "", 0, "", new OAuth2Credentials("", "", new string[] { }));
Configuration.GetSection("SMTP").Bind(smtpConfig);
这是结果:
希望对你有帮助
英文:
Because you are using record you have to give each parameter a default value in order to use it like this,
below code is the full example of usage:
public record SmtpConfiguration(string Name, string UserName, string Password, string HostName, int Port, string Security, OAuth2Credentials OAuth2);
public record OAuth2Credentials(string ClientId, string ClientSecret, string[] Scopes);
SmtpConfiguration smtpConfig = new SmtpConfiguration("", "", "", "", 0, "", new OAuth2Credentials("", "", new string[] { }));
Configuration.GetSection("SMTP").Bind(smtpConfig);
Here is the result
I hope it helps
答案2
得分: 0
你好!以下是翻译好的内容:
> 如何读取具有嵌套属性的.NET Core配置部分?
以下是一个工作示例,你可以参考它,希望能对你有所帮助。
-
将配置放入SmtpConfiguration.json文件中。
-
在你的Program.cs文件中添加以下代码(适用于asp.net core 6.0+):
var configuration = new ConfigurationBuilder()
.AddJsonFile("SmtpConfiguration.json")
.Build();
var Port = configuration.GetValue<int>("SMTP:Port");
IConfigurationSection myArraySection = configuration.GetSection("SMTP:OAuth2:Scopes");
var itemArray = myArraySection.AsEnumerable();
结果(为了测试,我将Scopes更改为"Scopes": [
"str1",
"str2",
"str3"
]):
你可以阅读ASP.NET Core中的配置和ASP.NET Core中的选项模式以了解更多信息。
英文:
> How can I read a .NET Core configuration section having nested
> properties?
Below is a work demo, you can refer to it, hope it can help.
1.Put configuration into SmtpConfiguration.json.
- Add below code to your Program.cs (asp.net core 6.0+):
var configuration = new ConfigurationBuilder()
.AddJsonFile("SmtpConfiguration.json")
.Build();
var Port = configuration.GetValue<int>("SMTP:Port");
IConfigurationSection myArraySection = configuration.GetSection("SMTP:OAuth2:Scopes");
var itemArray = myArraySection.AsEnumerable();
Result(For test, I change the Scopes to "Scopes": [
"str1",
"str2",
"str3"
]):
You can read Configuration in ASP.NET Core and Options pattern in ASP.NET Core to know more.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论