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;
        }
相关推荐
wqww_111 分钟前
springboot 使用websocket来记录移动人物坐标
spring boot·后端·websocket
一只幸运猫.17 分钟前
Rust实用工具特型-Clone
开发语言·后端·rust
0xDevNull28 分钟前
Java BigDecimal 完全指南:从入门到精通
java·开发语言·后端
无心水33 分钟前
17、Java内存溢出(OOM)避坑指南:三个典型案例深度解析
java·开发语言·后端·python·架构·java.time·java时间处理
咚为1 小时前
深入浅出 Rust 内存顺序:从 CPU 重排到 Atomic Ordering
开发语言·后端·rust
weixin_408099671 小时前
OCR 在线识别 + API 接口实战:从网页验证到系统集成
图像处理·人工智能·后端·ocr·api·图片文字识别·文字识别
crack_comet2 小时前
Spring Boot 3.5.11 分离打包(无参数启动+Jar瘦身)完整配置文档
java·spring boot·后端·maven·intellij-idea·jar
echome8882 小时前
Go 语言并发编程:Channel 与 Goroutine 的完美结合
开发语言·后端·golang
weixin_408099672 小时前
身份证正反面合并+识别OCR接口调用
java·人工智能·后端·python·ocr·api·身份证ocr
橘子编程2 小时前
Django全栈开发终极指南
后端·python·django·npm·html·pandas·html5