asp.net core configuration配置读取的实现
更新时间:2023年11月10日 08:59:31 作者:彭小彭~
本文主要介绍了asp.net core configuration配置读取,configuration可以从命令行、环境变量、配置文件读取配置,具有一定的参考价值,感兴趣的可以了解一下
asp.net core 默认注入了configuration配置服务,configuration可以从命令行、环境变量、配置文件读取配置。
这边主要演示从appsettings.json文件读取配置
1.读取单节点配置
{
"name":"pxp"
}
//在控制器注入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.读取嵌套节点
{
"info":{
"name":"pxp",
"age":"23",
"sex":"男"
}
}
//读取info里面的name
var 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;
}到此这篇关于asp.net core configuration配置读取的实现的文章就介绍到这了,更多相关asp.net core configuration配置 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
在IIS上重新注册.NET Framework 2.0的命令和参数详解
这篇文章主要介绍了在IIS上重新注册.NET Framework 2.0的命令和参数详解,但其它.NET Framework 版本没有测试,需要的朋友可以参考下2014-07-07
asp.net通过Ajax UpdatePanel回传后滚动条位置变更解决方法
用一个隐藏控件保存当前scorll值。回传回来后根据scroll的值在重新设置scroll。2010-06-06
asp.net继承IHttpHandler接口实现给网站图片添加水印功能实例
这篇文章主要介绍了asp.net继承IHttpHandler接口实现给网站图片添加水印功能,实例分析了asp.net基于IHttpHandler接口实现网站图片水印功能的具体步骤与相关技巧,需要的朋友可以参考下2016-07-07


最新评论