示例代码
Option
引用
第一个示例中的引用也要添加
Microsoft.Extensions.Options
在appsettings.json中添加测试数据
{
"MyData": {
"TotalCount": 2,
"Students": [
{
"Name": "Lili",
"Sex": "女"
},
{
"Name": "Tom",
"Sex": "男"
}
]
}
}
实体类需要实现IOptions<T>
public class ConfigTest:IOptions<ConfigTest>
{
public int TotalCount { get; set; }
public List<Student> Students { get; set; }
public ConfigTest Value => this;
}
读取json
public class ConfigController : Controller
{
private ConfigTest _configTestByOptions;
private readonly IConfiguration _configuration;
public ConfigController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
//GetSection:必须先读节点
//ConfigTest实现接口IOptions<ConfigTest>
_configTestByOptions = _configuration.GetSection("MyData").Get<ConfigTest>();
return View();
}
}
注意
CreateDefaultBuilder方法已经读取appsettings.json,所以在这个示例中,我们没有调用AddJsonFile方法添加appsettings.json文件,而是直接读取appsettings.json中的数据即可
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build(); |