asp.net?core?configuration配置讀取的實現(xiàn)
asp.net core 默認注入了configuration配置服務,configuration可以從命令行、環(huán)境變量、配置文件讀取配置。
這邊主要演示從appsettings.json文件讀取配置
1.讀取單節(jié)點配置
{
"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.讀取嵌套節(jié)點
{
"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;
}到此這篇關(guān)于asp.net core configuration配置讀取的實現(xiàn)的文章就介紹到這了,更多相關(guān)asp.net core configuration配置 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
asp.net利用HttpModule實現(xiàn)防sql注入
關(guān)于sql注入,已經(jīng)被很多人討論過了。這篇沒有新意功能也不夠通用,nnd,不想引起口水,就是覺得簡單而且思路有參考性才貼出來。2009-12-12
Visual Studio 2017無法加載Visual Studio 2015創(chuàng)建的SharePoint解決方法
這篇文章主要為大家詳細介紹了Visual Studio 2017無法加載Visual Studio 2015創(chuàng)建的SharePoint的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
asp.net連接數(shù)據(jù)庫讀取數(shù)據(jù)示例分享
這篇文章主要介紹了asp.net連接數(shù)據(jù)庫讀取數(shù)據(jù)示例,大家參考使用吧2014-01-01
.NET實現(xiàn)倉儲Repository(AI)的操作方法
倉儲模式是一種在應用程序中使用的設計模式,它將數(shù)據(jù)訪問邏輯與業(yè)務邏輯分離,通過倉儲接口和倉儲實現(xiàn)類,您可以定義和實現(xiàn)數(shù)據(jù)的增刪改查操作,這篇文章主要介紹了.NET?實現(xiàn)倉儲Repository(AI),需要的朋友可以參考下2023-09-09

