我有一个文件appsettings.json
,看起来像这样:
{
"MyConfig": {
"ConfigA": "value",
"ConfigB": "value"
}
}
在我的Startup.cs
我正在建立我的IConfiguration
:
public ConfigurationRoot Configuration { get; set; }
public Startup(ILoggerFactory loggerFactory, IHostingEnvironment environment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
//GetSection returns null...
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
但Configuration.GetSection("MyConfig")
总是返回null
,虽然该值存在于我的JSON文件中。 Configuration.GetSection("MyConfig:ConfigA")
工作得很好。
我究竟做错了什么?
请参考下面的代码
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var config = Configuration.GetSection("MyConfig");
// To get the value configA
var value = config["ConfigA"];
// or direct get the value
var configA = Configuration.GetSection("MyConfig:ConfigA");
var myConfig = new MyConfig();
// This is to bind to your object
Configuration.GetSection("MyConfig").Bind(myConfig);
var value2 = myConfig.ConfigA;
}
}
这对我有用。
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfig>(con=> Configuration.GetSection("MyConfig").Bind(con));
}
我刚碰到这个。如果您使用完整路径,那么值就在那里,但我需要将它们自动绑定到配置类。
我将自动属性访问器添加到我的类的属性后,.Bind(config)开始工作。即
public class MyAppConfig {
public string MyConfigProperty { get; set;} //this works
public string MyConfigProperty2; //this does not work
}
对于发生这种情况并试图在测试项目中做同样事情的人来说,这对我有用:
other = config.GetSection("OtherSettings").Get<OtherSettings>();