简体   繁体   English

绑定appsettings.json中的子配置以键入

[英]Binding subconfiguration in appsettings.json to type

I am trying to figure out how to bind a subsection of my appsettings.json to a class type. 我试图弄清楚如何将我的appsettings.json的子部分绑定到类类型。

Class

public class EmailProviderSettings : IEmailProviderSettings
{
    public string PopServer { get; set; }
    public int PopPort { get; set; }
    public string SmtpServer { get; set; }
    public int SmtpPortTls { get; set; }
    public int SmtpPortSsl { get; set; }
    public string ApiKey { get; set; }
    public bool UseSsl { get; set; }
    public string UserId { get; set; }
    public string UserPassword { get; set; }
    public string SentFromName { get; set; }
    public string SentFromEmail { get; set; }
}

appsettings.json appsettings.json

{
"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=92533D3BF281;Trusted_Connection=True;MultipleActiveResultSets=true"
},  
  "EmailConfigurations": {
     "Gmail": {
      "ApiKey": "",
      "UseSsl": true,
      "UserId": "me@gmail.com",
      "Password": "metootoo!",
      "SentFromName": "joe blo",
      "SentFromEmail": "joblo@xxxx.com",
      "PopServer": "pop.gmail.com",
      "PopPort": 995,
      "SmtpServer": "smtp.gmail.com",
      "SmtpPortSsl": 465,
      "SmtpPortTls": 587
    },
    "SendGrid": {
      "ApiKey": "SG.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "UseSsl": true,
      "UserId": "",
      "Password": "",
      "SentFromName": "Joe BLo",
      "SentFromEmail": "joblo@xxx.net",
      "PopServer": "",
      "PopPort": "",
      "SmtpServer": "smtp.sendgrid.com",
      "SmtpPortSsl": 465,
      "SmtpPortTls": 587
    }
  } 
}

In controller 在控制器中

 private readonly IConfiguration _config;

 public HomeController(IConfiguration config)
 {
     _config = config;
 }

and in ActionResult 并在ActionResult中

//my last effort which doesnt work
var providerSettings = new EmailProviderSettings();  
_config.GetSection("EmailConfigurations").GetSection("SendGrid").Bind(providerSettings);

and now how do I bind settings to an instance of EmailProviderSettings? 现在如何将设置绑定到EmailProviderSettings的实例? Error for this attempt is 此尝试的错误是

IndexOutOfRangeException: Index was outside the bounds of the array. IndexOutOfRangeException:索引超出数组的范围。

In your code, you are trying to bind "SendGrid" from the SendGrid section to the options. 在您的代码中,您试图将“ SendGrid”部分中的“ SendGrid”绑定到选项。

I think you meant: 我想你的意思是:

var configSection = _config.GetSection("EmailConfigurations").GetSection("SendGrid");
var settings = new EmailProviderSettings();
configSection.Bind(settings);

This binds the SendGrid section to your POCO. 这会将SendGrid部分绑定到您的POCO。

Also, it is a good idea to make the int members which can be empty to int? 另外,最好将可以为空的int成员设为int? eg: 例如:

public int? PopPort { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM