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;
        }
相关推荐
Moment2 小时前
AI 全栈指南:NestJs 中的 Service Provider 和 Module
前端·后端·面试
IT_陈寒2 小时前
为什么我的JavaScript异步回调总是乱序执行?
前端·人工智能·后端
Moment2 小时前
AI全栈入门指南:NestJs 中的 DTO 和数据校验
前端·后端·面试
小村儿2 小时前
Harness Engineering:为什么你用 AI 越用越累?
前端·后端·ai编程
小码哥_常2 小时前
为什么PUT和DELETE请求在大公司中逐渐被弃用?
后端
宫_商_角_徵2 小时前
动态代理到底在做什么?
后端
苍何2 小时前
我把微信 cli 开源了,群消息终于不用爬楼了!
后端
Moment2 小时前
当前端开始做 Agent 后,我才知道 LangGraph 有多重要❗❗❗
前端·后端·面试
小蜜蜂dry3 小时前
nestjs实战-登录、鉴权(一)
前端·后端·nestjs
苍何3 小时前
接入Seedance 2.0 后的 OiiOii,太让人上头了!
后端