我正在尝试从 appsettings.json 中读取数据。
emailConfig
中的 ApiController
始终为空。我尝试使用Options pattern读取数据,但是它不起作用。
控制器
private EmailConfiguration emailConfig;
public ApiController (IOptions<EmailConfiguration> _emailConfig) {
this.emailConfig=_emailConfig.Value;
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "connectionstring here"
},
"EmailConfiguration": {
"SmtpServer": "smtp.zoho.com",
"SmtpPort": 587,
"SmtpUsername": "username.zoho.com",
"SmtpPassword": "password"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
将appsettings.json加载到配置文件(Startup.cs)
Configuration = new ConfigurationBuilder ()
.SetBasePath (env.ContentRootPath)
.AddJsonFile ("appsettings.json", optional : true, reloadOnChange : true)
.AddJsonFile ($"appsettings.{env.EnvironmentName}.json", optional : true)
.AddEnvironmentVariables ()
.Build ();
Startup.cs // // ConfigureServices()
services.Configure<EmailConfiguration>(Configuration);
services.AddSingleton<IEmailConfiguration> (Configuration.GetSection ("EmailConfiguration").Get<EmailConfiguration> ());
services.AddSingleton<IEmailConfiguration> (sp =>
sp.GetRequiredService<IOptions<EmailConfiguration>> ().Value
);
EmailConfiguration.cs
public class EmailConfiguration : IEmailConfiguration {
public EmailConfiguration(){
}
public string SmtpServer { get; set; }
public int SmtpPort { get; set; }
public string SmtpUsername { get; set; }
public string SmtpPassword { get; set; }
}
答案 0 :(得分:2)
调用Configure
时,您需要指定该部分以绑定设置文件的所需部分
services.Configure<EmailConfiguration>(Configuration.GetSection("EmailConfiguration"));
由于您现在已经注册了该选项,并且您似乎还想将其注册为单例,请考虑以下内容
services.AddSingleton<IEmailConfiguration> (sp =>
sp.GetRequiredService<IOptions<EmailConfiguration>>().Value
);