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;
        }
相关推荐
安当加密41 分钟前
Spring Boot应用接入国产安当凭据管理系统SMS Starter实战(附源码)
java·spring boot·后端
树下水月1 小时前
Easyswoole 框架session在高并发/频繁请求下数据丢失问题记录
java·后端·spring
用户6757049885021 小时前
密码泄露了?别慌!GitHub、微软、Google都在用的“虚拟MFA”,到底有多强?
后端·安全
源图客1 小时前
Go语言goland代码编辑与调试
开发语言·后端·golang
用户6757049885021 小时前
改了DNS还是不生效?Ubuntu 24.04的这个坑我帮你踩过了
后端·ubuntu·dns
文心快码BaiduComate1 小时前
Comate Spec模式实践:电商视频自动化生产数据库eDB-MCP服务开发
前端·后端·架构
神奇小汤圆1 小时前
我想带你动手走一遍最简单的 Harness Engineering
后端
卷无止境1 小时前
Rust写大型项目时,编译太慢怎么办?
后端
星栈2 小时前
多租户隔离,我选择"倒退"后开发速度直接翻了 3 倍
后端
敖正炀2 小时前
手写简易 MyBatis 框架(mini-mybatis)—— 完善版架构设计与核心实现
后端·mybatis