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;
        }
相关推荐
怒放吧德德2 小时前
Spring Boot实战:InfluxDB 2.x简单教程
java·spring boot·后端
后端不背锅2 小时前
可观测性体系:日志、指标、链路追踪
后端
苍何2 小时前
把小度音箱接入小龙虾是一种什么体验?
后端
华科易迅2 小时前
Spring AOP
java·后端·spring
架构师沉默2 小时前
Gemini 正式登陆香港,不用翻墙!
java·后端·架构
zihao_tom3 小时前
Spring WebFlux:响应式编程
java·后端·spring
想打游戏的程序猿3 小时前
从零理解 LLM 与 Agent
后端·ai编程
wooyoo3 小时前
花了一周 vibe 了一个 OpenClaw 的 Agent 市场,聊聊过程中踩的坑
前端·后端·agent
树獭叔叔3 小时前
文本Embedding模型演进:从Encoder-only到LLM-based的技术变革
后端·aigc·openai
游离态指针3 小时前
首字节响应 0ms?我用 1000 行代码驯服了 Spring AI Agent 的“不确定性”
后端