如何从 IConfigurationSection 转换为通用列表?

问题描述 投票:0回答:1

如何从 IConfigurationSection 转换为通用字符串列表?我希望将电子邮件列表添加到从 appsettings.json 读取的代码中。 .Get(); 不起作用。我没有从 IConfigurationSection 的 microsoft 文档中了解如何执行此操作。

电子邮件服务.cs

public class EmailService : IEmailService
{
    private readonly IConfiguration _configuration;

    public EmailService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

   public Task<IEnumerable<string>> GetDistributionWhitelist()
   {
     var emails = _configuration.GetSection("DistributionWhitelist:Emails").Get<List<string>>();
     return emails;
   }
}

应用程序设置.json

"DistributionWhitelist": {
  "Emails": [
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]"
  ]
}
c# .net
1个回答
0
投票
public Task<IEnumerable<string>> GetDistributionWhitelist()
{
var emails = _configuration.GetSection("DistributionWhitelist:Emails").Get<IEnumerable<string>>();
return Task.FromResult(emails?? new List<string>());
}

用这个替换方法。

© www.soinside.com 2019 - 2024. All rights reserved.