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;
        }
相关推荐
有来技术3 小时前
Spring Boot 4 + Vue3 企业级多租户 SaaS:从共享 Schema 架构到商业化套餐设计
java·vue.js·spring boot·后端
东东5165 小时前
学院个人信息管理系统 (springboot+vue)
vue.js·spring boot·后端·个人开发·毕设
三水不滴5 小时前
Redis缓存更新策略
数据库·经验分享·redis·笔记·后端·缓存
小邓吖6 小时前
自己做了一个工具网站
前端·分布式·后端·中间件·架构·golang
大爱编程♡6 小时前
SpringBoot统一功能处理
java·spring boot·后端
好好研究9 小时前
总结SSM设置欢迎页的方式
xml·java·后端·mvc
小马爱打代码9 小时前
Spring Boot:第三方 API 调用的企业级容错设计
java·spring boot·后端
csdn2015_10 小时前
springboot task
java·spring boot·后端
czlczl2002092511 小时前
Spring Boot :如何高性能地在 Filter 中获取响应体(Response Body)
java·spring boot·后端
码界奇点11 小时前
基于Spring Boot和Vue3的无头内容管理系统设计与实现
java·spring boot·后端·vue·毕业设计·源代码管理