- 安装依赖包,由于我是用的是core 2.0 版本,安装的包版本可能和你的有区别
- 定义实体类以及json文件添加
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"test": {
"name":"123"
},
"AllowedHosts": "*"
}
RootConfig类这个类的结构和json文件一样
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication.Config
{
public class RootConfig
{
public Logging Logging { get; set; }
public string AllowedHosts { get; set; }
public test test { get; set; }
}
public class Logging
{
public LogLevel LogLevel { get; set; }
}
public class LogLevel
{
public string Default { get; set; }
}
public class test
{
public string name { get; set; }
}
}
GetConfig类这里只是获取test这一个节点
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace WebApplication.Config
{
public class GetConfig
{
private readonly IOptionsSnapshot<test> _optionsSnapshot;
public GetConfig(IOptionsSnapshot<test> optionsSnapshot)
{
_optionsSnapshot = optionsSnapshot;
}
public test getByName()
{
return _optionsSnapshot.Value;
}
}
}
startup.cs
只是获取test这个节点,要获取整个的json ,只需要将test替换成rootconfig,并删除configurationRoot.GetSection(“test”).Bind(x)
替换成configurationRoot.Bind(x)
services.AddScoped<GetConfig>();
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfigurationRoot configurationRoot = configurationBuilder.Build();
services.AddOptions().Configure<test>(x => configurationRoot.GetSection("test").Bind(x));
var ss = services.BuildServiceProvider().GetRequiredService<GetConfig>().getByName();