我无法从 .NET Core 中的 appsettings 文件接收配置值。
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"PortedConfig": {
"ConfigTableAccess": "ConfigTableConnectionString",
"ConfigTableName": "Config"
}
}
startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
var config = Configuration;
var settings = Configuration.GetSection("PortedConfig").Get<PortedConfig>();
services.Configure<PortedConfig>(options => Configuration.GetSection("PortedConfig").Bind(options));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddScoped<IEncryptManager, EncryptManager>()
.AddScoped<IDecryptManager, DecryptManager>();
}
PortedConfig.cs:
public class PortedConfig
{
public string ConfigTableAccess;
public string ConfigTableName;
}
在 startup.cs
中,在运行时配置被填充,但是当我使用 GetSection
时,值为空,如下图所示:
如上图所示,ConfigTableAccess
和 ConfigTableName
在设置变量中为空。
最佳答案
将字段更改为属性,不要忘记公共(public) setter 。
public class PortedConfig
{
public string ConfigTableAccess { get; set; }
public string ConfigTableName { get; set; }
}
关于c# - 尝试使用启动文件中的 GetSection 访问它们时,配置值为空。(IOptions-config 检索),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249653/