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;
        }
相关推荐
一个做软件开发的牛马10 分钟前
MyBatis 从零实战:完整搭建可运行 Demo,注解与 XML 双模式开发详解
java·后端
砍材农夫15 分钟前
python环境|conda安装和使用(1)
开发语言·后端·python·conda
用户2986985301415 分钟前
Java 实践:查找与提取 Word 文档超链接
java·后端
Rust研习社16 分钟前
Rust 错误处理的黄金搭档:一个定义错误,一个传播错误
后端·rust·编程语言
Moment17 分钟前
从多人编辑到 Agent 写文档,Hocuspocus v4 正在改写协同系统 😍😍😍
前端·后端·面试
贺国亚25 分钟前
评估-Eval-Hallucination与质量度量
后端·面试
Java内核笔记26 分钟前
Spring Security 源码解析(五)表单登录认证全流程:UsernamePasswordAuthenticationFilter 拆解
后端
Dilee29 分钟前
Spring AI 对话记忆:MessageChatMemoryAdvisor 最小接入
后端
游码峰行32 分钟前
游戏脚本挂攻防-在PoW中实现动态Hash策略及应用实践
后端
一条泥憨鱼32 分钟前
苍穹外卖【day6|微信登录与商品浏览功能】
后端·mybatis·苍穹外卖