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;
        }
相关推荐
涡能增压发动积13 小时前
同样的代码循环 10次正常 循环 100次就抛异常?自定义 Comparator 的 bug 让我丢尽颜面
后端
Wenweno0o13 小时前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
swg32132113 小时前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
tyung13 小时前
一个 main.go 搞定协作白板:你画一笔,全世界都看见
后端·go
gelald13 小时前
SpringBoot - 自动配置原理
java·spring boot·后端
殷紫川14 小时前
深入拆解 Java 内存模型:从原子性、可见性到有序性,彻底搞懂 happen-before 规则
java·后端
元宝骑士14 小时前
FIND_IN_SET使用指南:场景、优缺点与MySQL优化策略
后端·mysql
用户319523703477114 小时前
记一次 PostgreSQL WAL 日志撑爆磁盘的排查
后端
nghxni14 小时前
LightESB PlatformHttp v3.0.0:JSONPath 订单转换 HTTP 路由实战
后端
武子康14 小时前
大数据-263 实时数仓-Canal 增量订阅与消费原理:MySQL Binlog 数据同步实践
大数据·hadoop·后端