继续关于Using IConfiguration globally in mvc6的StackOverflow问题。对已接受答案的评论建议使用
services.Configure<SomeOptions>(Configuration);
现在使用以下代码可以正常工作;
类
public class SomeOptions
{
public string MyOption { get; set; }
}
config.json
{
"MyOption": "OptionValue"
}
Startup.cs
public Startup(IHostingEnvironment env)
{
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SomeOptions>(Configuration);
}
然而,config.json
文件没有任何真正的结构,我希望它看起来更像;
{
"SomeOptions": {
"MyOption": "OptionValue"
}
}
但是,这不会绑定类中的值。无论如何都允许这个吗?
答案 0 :(得分:2)
如果您想更改config.json
结构,还需要更改类结构。
{
"SomeOptions": {
"MyOption": "OptionValue"
}
}
映射到类似
的内容public class SomeOptions
{
public List<MyOption> MyOptions { get; set; }
}
public class MyOption
{
public string OptionValue { get; set; }
}
答案 1 :(得分:1)
您可以在config.json中访问特定值,如:
Configuration.Get("SomeOptions:MyOption");
返回
"OptionValue"
所以,你的代码将是
services.Configure<SomeOptions>(options =>
options.MyOption = Configuration.Get("SomeOptions:MyOption"));
答案 2 :(得分:0)
{
"data" : [
{
"_id" : 36,
"lat" : 36.1212111,
"lon" : 127.2312112
},
{
"_id" : 37,
"lat" : 36.1212111,
"lon" : 127.9817112
},
{
"_id" : 38,
"lat" : 36.1212111,
"lon" : 128.2312112
},
{
"_id" : 39,
"lat" : 36.1212111,
"lon" : 128.8312112
}
],
"uuid" : 999999999
}
{
"data" : [
{
"_id" : 30,
"lat" : 36.1212111,
"lon" : 120.2312112
},
{
"_id" : 31,
"lat" : 36.1212111,
"lon" : 120.2345112
},
{
"_id" : 32,
"lat" : 36.1212111,
"lon" : 120.2378112
},
{
"_id" : 33,
"lat" : 36.1212111,
"lon" : 120.2378112
},
{
"_id" : 34,
"lat" : 36.1212111,
"lon" : 120.2423112
},
{
"_id" : 35,
"lat" : 36.1212111,
"lon" : 120.2467112
}
],
"uuid" : 123123123
}
应该这样做。