[英]Binding subconfiguration in appsettings.json to type
我试图弄清楚如何将我的appsettings.json的子部分绑定到类类型。
类
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
}
}
}
在控制器中
private readonly IConfiguration _config;
public HomeController(IConfiguration config)
{
_config = config;
}
并在ActionResult中
//my last effort which doesnt work
var providerSettings = new EmailProviderSettings();
_config.GetSection("EmailConfigurations").GetSection("SendGrid").Bind(providerSettings);
现在如何将设置绑定到EmailProviderSettings的实例? 此尝试的错误是
IndexOutOfRangeException:索引超出数组的范围。
在您的代码中,您试图将“ SendGrid”部分中的“ SendGrid”绑定到选项。
我想你的意思是:
var configSection = _config.GetSection("EmailConfigurations").GetSection("SendGrid");
var settings = new EmailProviderSettings();
configSection.Bind(settings);
这会将SendGrid部分绑定到您的POCO。
另外,最好将可以为空的int
成员设为int?
例如:
public int? PopPort { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.