0


asp.net core configuration配置读取

asp.net core 默认注入了configuration配置服务,configuration可以从命令行、环境变量、配置文件读取配置。
这边主要演示从appsettings.json文件读取配置
1.读取单节点配置

{"name":"pxp"}
//在控制器注入IconfigurationprivateIConfiguration _configuration;publicWeatherForecastController(IConfiguration configuration){
            _configuration = configuration;}[HttpGet(Name ="GetWeatherForecast")]publicIEnumerable<WeatherForecast>Get(){var name = _configuration.GetSection("name");
            Console.WriteLine("读取配置:"+ name );returnnull;}

2.读取嵌套节点

{"info":{"name":"pxp","age":"23","sex":"男"}}
//读取info里面的namevar name = _configuration.GetSection("info:name");

3.映射到实体

publicclassInfo{publicstring name{get;set;}publicstring age{get;set;}publicstring sex{get;set;}}
var info= _configuration.GetSection("info");string name= info.get<info>().name;

4.注入服务,映射到实体

//在program中注入// 读取配置到实体类
 builder.Services.Configure<Info>(builder.Configuration.GetSection("Info"));

//使用Ioptions接口接收

privatereadonlyIOptions<Info> _myConfig;publicWeatherForecastController(IOptions<Info> myConfigOptions){
            _myConfig = myConfigOptions;
            _configuration = configuration;}[HttpGet(Name ="GetWeatherForecast")]publicIEnumerable<WeatherForecast>Get(){
            Console.WriteLine("读取配置:"+ _myConfig.Value.name);returnnull;}
标签: asp.net 后端

本文转载自: https://blog.csdn.net/qq_41942413/article/details/134323873
版权归原作者 彭小彭~ 所有, 如有侵权,请联系我们删除。

“asp.net core configuration配置读取”的评论:

还没有评论