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;
        }
相关推荐
aq553560025 分钟前
SpringBoot有几种获取Request对象的方法
java·spring boot·后端
dotNET实验室29 分钟前
ASP.NET Core 外部依赖调用治理实战:HttpClientFactory、Polly 与幂等边界
后端
Nturmoils39 分钟前
从「亡羊补牢」到「规则先行」:金仓数据库 SQL 防火墙实战解析
数据库·后端
Oneslide1 小时前
Harbor 启动失败故障排查与解决:从“Cannot allocate memory”到“Operation not permitted”
后端
神超1 小时前
AgentScope 入门:用 Java 快速搭一个可用的 Agent
后端
码事漫谈1 小时前
防患未然,金仓数据库SQL防火墙筑牢数据安全“第一道门”
后端
宸翰1 小时前
Python学习:年轻人的第一个入门Python项目(FastAPI版)
后端·python
Moment1 小时前
MiniMax 发布 M2.7,Agent 开始走向自我进化
前端·后端·面试
肌肉娃子1 小时前
2026.3.18.为什么doris冷启动查询如此之慢呢
后端
兴趣使然的草帽路飞1 小时前
6w字汇总下最近背过的Java服务端面试题笔记
后端