asp.net core configuration配置读取

asp.net core 默认注入了configuration配置服务,configuration可以从命令行、环境变量、配置文件读取配置。

这边主要演示从appsettings.json文件读取配置

1.读取单节点配置

csharp 复制代码
{
"name":"pxp"
}
csharp 复制代码
//在控制器注入Iconfiguration
  private IConfiguration _configuration;
  public WeatherForecastController( IConfiguration configuration)
        {
            _configuration = configuration;
        }
       [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            var name = _configuration.GetSection("name");
            Console.WriteLine("读取配置:" + name );
            return null;
        }

2.读取嵌套节点

csharp 复制代码
{
"info":{
 "name":"pxp",
 "age":"23",
 "sex":"男"
}
}
csharp 复制代码
//读取info里面的name
 var name = _configuration.GetSection("info:name");

3.映射到实体

csharp 复制代码
public class Info
{
public string name{get;set;}
public string age{get;set;}
public string sex{get;set;}
}
csharp 复制代码
var info= _configuration.GetSection("info");
string name= info.get<info>().name;

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

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

//使用Ioptions接口接收

csharp 复制代码
private readonly IOptions<Info> _myConfig;
public WeatherForecastController(IOptions<Info> myConfigOptions)
        {
            _myConfig = myConfigOptions;
            _configuration = configuration;
        }
        
        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            Console.WriteLine("读取配置:" + _myConfig.Value.name);
            return null;
        }
相关推荐
一条Go18 分钟前
巡检报告:把一次性排障变成可复跑的任务
后端·github
一条Go31 分钟前
SQL 实验室:只读靠两把锁,DDL 靠模板
后端·github
一条Go34 分钟前
维护窗口与升级策略:静默和升级怎么共存
后端·github
一条Go34 分钟前
应用商店:版本、发布与部署为什么必须拆成三个阶段
后端·github
京东云开发者1 小时前
一份数据,两种协议:京东云存储打通文件与对象
后端
CRZZX4 小时前
ManagedAgent 设计与使用
后端·agent
狗头大军之江苏分军6 小时前
三个月的电商心得
前端·后端
JuiceFS6 小时前
4300万请求零崩溃:基于 JuiceFS 的 WordPress 高并发加速实践
后端
软件技术NINI7 小时前
基于SpringBoot的社区留守儿童帮扶系统
java·spring boot·后端
挖掘狂人7 小时前
为什么造手表的人,先造出了 “软件工厂”?
后端·ai编程