简体   繁体   中英

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.

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

{
"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

//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? Error for this attempt is

IndexOutOfRangeException: Index was outside the bounds of the array.

In your code, you are trying to bind "SendGrid" from the SendGrid section to the options.

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.

Also, it is a good idea to make the int members which can be empty to int? eg:

public int? PopPort { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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