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;
        }
相关推荐
paopaokaka_luck3 小时前
基于Springboot3+Vue3的宠物殡葬管理系统(webSocket实时通讯、接入腾讯地图、支付宝沙盒支付、Echarts图形化分析)
java·开发语言·网络·后端
卷无止境3 小时前
Python 中基于 Qt 的 GUI 库授权方式全解析
后端·python
程序员爱钓鱼3 小时前
Rust 注释与文档注释详解:从代码说明到 cargo doc
后端·rust
前鼻音太阳熊3 小时前
【MES系统】MES为什么需要SSE?从设备实时监控谈Spring Boot流式推送设计
java·spring boot·后端
卷无止境4 小时前
Guardrails.ai:为大语言模型加一道"安全阀"
后端·python
尚早立志4 小时前
六)Spring Boot 源码研读之prepareContext 准备上下文
java·spring boot·后端·spring
Dovis(誓平步青云)5 小时前
《Linux CPU频率为何忽高忽低:cpufreq、idle状态与性能抖动教程》
linux·运维·服务器·spring boot·后端·生成对抗网络
To_OC12 小时前
手写 AI 编程 Agent 的命令执行工具:我被 child_process 坑出来的实战经验
后端·node.js·agent
逝水无殇14 小时前
C# 异常处理详解
开发语言·后端·c#
考虑考虑17 小时前
Sentinel安装
java·后端·微服务