你可以使用 Configuration GetRequiredSection() 方法来读取对象树。

huangapple go评论99阅读模式
英文:

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):

{
  &quot;SMTP&quot;:
  {
    &quot;Name&quot;: &quot;...&quot;,
    &quot;UserName&quot;: &quot;...&quot;,
    &quot;Password&quot;: &quot;...&quot;,
    &quot;HostName&quot;: &quot;...&quot;,
    &quot;Port&quot;: &quot;587&quot;,
    &quot;Security&quot;: &quot;STARTTLS&quot;,
    &quot;OAuth2&quot;:
    {
      &quot;ClientId&quot;: &quot;&quot;,
      &quot;ClientSecret&quot;: &quot;&quot;,
      &quot;Scopes&quot;:
      [
      ]
    }
  }
}

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(&quot;SMTP&quot;)
  .Get&lt;SmtpConfiguration&gt;()!;

… I get the following error:

System.InvalidOperationException: Cannot create instance of type
&#39;WebApi.SendEMail.SmtpConfiguration&#39; because parameter &#39;OAuth2&#39; 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&lt;string&gt;();
}

public record SmtpConfiguration(string Name, string UserName, string Password, string HostName, int Port, string Security)
{
  public OAuth2Credentials OAuth2 = new OAuth2Credentials(&quot;&quot;, &quot;&quot;);
}


try
{
  smtpConfig = Program.Configuration!.GetRequiredSection(&quot;SMTP&quot;).Get&lt;SmtpConfiguration&gt;()!;
  smtpConfig.OAuth2 = Program.Configuration!.GetRequiredSection(&quot;SMTP:OAuth2&quot;).Get&lt;OAuth2Credentials&gt;()!;
  smtpConfig.OAuth2.Scopes = Program.Configuration!.GetRequiredSection(&quot;SMTP:OAuth2:Scopes&quot;).Get&lt;string[]&gt;()!;
}
catch (InvalidOperationException ex) { return TypedResults.BadRequest($&quot;Invalid SMTP configuration: {ex.Message}&quot;); }

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);

这是结果:

你可以使用 Configuration GetRequiredSection() 方法来读取对象树。

希望对你有帮助 你可以使用 Configuration GetRequiredSection() 方法来读取对象树。

英文:

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(&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, 0, &quot;&quot;, new OAuth2Credentials(&quot;&quot;, &quot;&quot;, new string[] { }));

Configuration.GetSection(&quot;SMTP&quot;).Bind(smtpConfig);

Here is the result

你可以使用 Configuration GetRequiredSection() 方法来读取对象树。

I hope it helps 你可以使用 Configuration GetRequiredSection() 方法来读取对象树。

答案2

得分: 0

你好!以下是翻译好的内容:

> 如何读取具有嵌套属性的.NET Core配置部分?

以下是一个工作示例,你可以参考它,希望能对你有所帮助。

  1. 将配置放入SmtpConfiguration.json文件中。

  2. 在你的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"
]):

你可以使用 Configuration GetRequiredSection() 方法来读取对象树。

你可以阅读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.

  1. Add below code to your Program.cs (asp.net core 6.0+):
    var configuration = new ConfigurationBuilder()
        .AddJsonFile(&quot;SmtpConfiguration.json&quot;)
        .Build();
    var Port = configuration.GetValue&lt;int&gt;(&quot;SMTP:Port&quot;);
    IConfigurationSection myArraySection = configuration.GetSection(&quot;SMTP:OAuth2:Scopes&quot;);
    var itemArray = myArraySection.AsEnumerable();

Result(For test, I change the Scopes to "Scopes": [
"str1",
"str2",
"str3"
]):

你可以使用 Configuration GetRequiredSection() 方法来读取对象树。

You can read Configuration in ASP.NET Core and Options pattern in ASP.NET Core to know more.

huangapple
  • 本文由 发表于 2023年8月9日 08:30:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76863860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定