[英]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.