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;
        }
相关推荐
IT_陈寒20 分钟前
Vue的动态组件坑了我整整一天!
前端·人工智能·后端
Cobyte23 分钟前
AI 的个人便签纸:Claude Code 的 TodoWrite 模式
前端·后端·aigc
hai31524754324 分钟前
FiveOS V3.0 交付(微服务器操作系统版 · 物理合规修正
linux·人工智能·spring boot·后端·神经网络·机器学习
硅农深芯29 分钟前
芯片设计后端工作流程详解
后端·芯片设计
Oneslide39 分钟前
mysql备份指定表
后端
逍遥德1 小时前
PostgreSQL ---【序列】用法详解
数据库·后端·sql·postgresql
逍遥德1 小时前
PostgreSQL --- 自增主键【序列】的避坑指南
数据库·后端·sql·mysql·postgresql·sqlserver
段ヤシ.1 小时前
【Java框架】知识点汇总Day7:Spring Boot +Vue(持续更新)
vue.js·spring boot·后端·框架
土狗TuGou1 小时前
SQL进阶笔记 · 第1篇:存储引擎
java·数据库·笔记·后端·sql·mysql
码语智行1 小时前
Spring Security自定义AuthenticationManager实现手机号/密码双认证
java·后端·spring