我试图找出如何将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:索引超出了数组的范围。
答案 0 :(得分:2)
在您的代码中,您正试图绑定" SendGrid"从SendGrid部分到选项。
我认为你的意思是:
<nav>
<div id="navbar">
<ul id="navbar-list">
<li>
<a class="pocetna" href="#"><img src="img/logo icon.ico" width="30" height="30" style="padding-right:10px;">Masaže Gligorijević</a>
</li>
<li class="linkovil"><a class="linkovi" href="#">Početna</a></li>
<li class="linkovil"><a class="linkovi" href="#section1">O nama</a></li>
<li><a class="linkovi m" href="#section2">Kontakt</a></li>
</ul>
</div>
</nav>
<header>
<div id="main">
<h1>Masaže Gligorijević</h1>
<h3>Ulaganjem u svoje zdravlje, ulažete u kvalitet sopstvenog života.</h3>
<hr>
<button class="button"><i class="fas fa-play"></i> <a href="#section2">Rezervišite Odmah</a></button>
</div>
</header>
<section>
<video autoplay muted loop id="video">
<source src="klip.mp4" type="video/mp4">
</video>
<div id="section1">
<h3>O nama</h3>
<p>
</p>
</div>
</section>
这会将SendGrid部分绑定到您的POCO。
此外,最好将var configSection = _config.GetSection("EmailConfigurations").GetSection("SendGrid");
var settings = new EmailProviderSettings();
configSection.Bind(settings);
成员清空为int
,例如:
int?