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;
        }
相关推荐
程序员老赵5 小时前
Docker 部署 DeepSeek Harness:轻松搭建局域网里的 AI Agent 平台
后端·ai编程·deepseek
YIAN5 小时前
实战|用 DeepSeek + SQLite 从零搭建轻量 Text2SQL 查询助手
后端·sqlite·deepseek
王中阳Go5 小时前
自己摸了 2 个月零 offer,补底子只用了 3 块:Go 后端转 AI 最难的不是技术
后端·agent·ai编程
高频因子挖掘机5 小时前
第一次补历史行情:按股票拆,还是按日期拆请求?
后端·github·api
小园子的小菜5 小时前
Python协程深度解析:从原理演进到实战避坑
后端·python
高频因子挖掘机5 小时前
300 只股票 × 两年日 K:为什么逐只循环会变成维护灾难?
后端·github·api
苏三说技术6 小时前
Spring AI Alibaba已停更了,Java还有希望吗?
后端
松就是我902987 小时前
如何搭建一个 Agent 系统:方法论、理想形态与一次真实落地
后端
Layer7 小时前
即时通讯系统的关键设计
后端·架构
golang学习记8 小时前
rust开发,选VS Code还是RustRover?
开发语言·后端·rust