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;
        }
相关推荐
Joker`s smile7 分钟前
Spring Cloud Alibaba 基础入门实践
java·spring boot·后端·spring cloud
Victor3567 分钟前
MongoDB(68)如何使用mongoexport和mongoimport?
后端
Victor35611 分钟前
MongoDB(67)如何使用mongodump和mongorestore?
后端
散峰而望28 分钟前
【数据结构】单调栈与单调队列深度解析:从模板到实战,一网打尽
开发语言·数据结构·c++·后端·算法·github·推荐算法
无籽西瓜a38 分钟前
【西瓜带你学设计模式 | 第一期-单例模式】单例模式——定义、实现方式、优缺点与适用场景以及注意事项
java·后端·单例模式·设计模式
William_cl38 分钟前
[特殊字符]C# ASP.NET Core 前后端分离终极实战:JWT 身份认证与授权全流程(登录 + 鉴权 + 避坑)
c#·asp.net·状态模式
imuliuliang41 分钟前
Spring Boot(快速上手)
java·spring boot·后端
yashuk1 小时前
Spring Boot 3.4 正式发布,结构化日志!
java·spring boot·后端
想打游戏的程序猿11 小时前
核心概念层——深入理解 Agent 是什么
后端·ai编程
woniu_maggie12 小时前
SAP Web Service日志监控:如何用SRT_UTIL快速定位接口问题
后端