• asp.net core configuration配置读取


    asp.net core 默认注入了configuration配置服务,configuration可以从命令行、环境变量、配置文件读取配置。
    这边主要演示从appsettings.json文件读取配置
    1.读取单节点配置

    {
    "name":"pxp"
    }
    
    • 1
    • 2
    • 3
    //在控制器注入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;
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2.读取嵌套节点

    {
    "info":{
     "name":"pxp",
     "age":"23",
     "sex":"男"
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    //读取info里面的name
     var name = _configuration.GetSection("info:name");
    
    • 1
    • 2

    3.映射到实体

    public class Info
    {
    public string name{get;set;}
    public string age{get;set;}
    public string sex{get;set;}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    var info= _configuration.GetSection("info");
    string name= info.get<info>().name;
    
    • 1
    • 2

    4.注入服务,映射到实体

     //在program中注入
     // 读取配置到实体类
     builder.Services.Configure<Info>(builder.Configuration.GetSection("Info"));
    
    • 1
    • 2
    • 3

    //使用Ioptions接口接收

    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;
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    系分 - 数学与经济管理
    C++调用Python(傻瓜式教学)
    vue 01
    (附源码)spring boot投票系统 毕业设计 261136
    安卓性能优化手册
    【Web安全】SQL各类注入与绕过
    day08PKI以及综合实验
    taichi 和正常python 速度对比
    【Spring(二)】java对象属性的配置(Bean的配置)
    C++仿函数真好用
  • 原文地址:https://blog.csdn.net/qq_41942413/article/details/134323873