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;
        }
相关推荐
无风听海8 小时前
深入剖析 YARP 的 Transforms:构建灵活的反向代理转换管道
后端·中间件·asp.net
Gopher_HBo8 小时前
负载均衡
后端
自由生长20249 小时前
RAG已死?什么标题党啊!
后端
东方小月9 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构
折哥的程序人生 · 物流技术专研12 小时前
Java面试85题图解版(一):基础核心篇
java·开发语言·后端·面试
Moment13 小时前
面试官:如果产品经理给你多个需求,怎么让AI去完成❓❓❓
前端·后端·面试
每天进步一点_JL13 小时前
JVM 内存模型与 OOM 排查:从入门到实战
后端
REDcker14 小时前
个人博客网站建设指南 Markdown资产化与静态站选型部署
前端·后端·博客·markdown·网站·资产·建站
Supersist14 小时前
【设计模式03】使用模版模式+责任链模式优化实战
后端·设计模式·代码规范
Fox爱分享14 小时前
字节二面:10亿数据毫秒级查手机尾号后4位,答不出“异构索引”直接挂?
java·后端·面试