当前位置:首页 > 编程笔记 > 正文
已解决

asp.net core configuration配置读取

来自网友在路上 156856提问 提问时间:2023-11-10 05:15:47阅读次数: 56

最佳答案 问答题库568位专家为你答疑解惑

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

{
"name":"pxp"
}
//在控制器注入Iconfigurationprivate 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.读取嵌套节点

{
"info":{"name":"pxp","age":"23","sex":"男"
}
}
//读取info里面的namevar name = _configuration.GetSection("info:name");

3.映射到实体

public class Info
{
public string name{get;set;}
public string age{get;set;}
public string sex{get;set;}
}
var info= _configuration.GetSection("info");
string name= info.get<info>().name;

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

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

//使用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;}
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"asp.net core configuration配置读取":http://eshow365.cn/6-36921-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!