我试图弄清楚如何将我的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": "[email protected]",
"Password": "metootoo!",
"SentFromName": "joe blo",
"SentFromEmail": "[email protected]",
"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": "[email protected]",
"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; }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句