asp.net core 默认注入了configuration配置服务,configuration可以从命令行、环境变量、配置文件读取配置。
这边主要演示从appsettings.json文件读取配置
1.读取单节点配置
1 2 3 | { "name" : "pxp" } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | //在控制器注入Iconfiguration private IConfiguration _configuration; public WeatherForecastController( IConfiguration configuration) { _configuration = configuration; } [HttpGet(Name = "GetWeatherForecast" )] public IEnumerable Get() { var name = _configuration.GetSection( "name" ); Console.WriteLine( "读取配置:" + name ); return null ; } |
2.读取嵌套节点
1 2 3 4 5 6 7 | { "info" :{ "name" : "pxp" , "age" : "23" , "sex" : "男" } } |
1 2 | //读取info里面的name var name = _configuration.GetSection( "info:name" ); |
3.映射到实体
1 2 3 4 5 6 | public class Info { public string name{ get ; set ;} public string age{ get ; set ;} public string sex{ get ; set ;} } |
1 2 | var info= _configuration.GetSection( "info" ); string name= info. get ().name; |
4.注入服务,映射到实体
1 2 3 | //在program中注入 // 读取配置到实体类 builder.Services.Configure(builder.Configuration.GetSection( "Info" )); |
//使用Ioptions接口接收
1 2 3 4 5 6 7 8 9 10 11 12 13 | private readonly IOptions _myConfig; public WeatherForecastController(IOptions myConfigOptions) { _myConfig = myConfigOptions; _configuration = configuration; } [HttpGet(Name = "GetWeatherForecast" )] public IEnumerable Get() { Console.WriteLine( "读取配置:" + _myConfig.Value.name); return null ; } |
到此这篇关于asp.net core configuration配置读取的实现的文章就介绍到这了,更多相关asp.net core configuration配置 内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!