ASP.NET core Web中使用appsettings.json配置文件的方法
前言
最近在研究把asp.net程序移植到linux上,正好.netcore出来了,就进行了学习。
移植代码基本顺利,但是发现.netcore中没有ConfigurationManager,无法读写配置文件,单独写个xml之类的嫌麻烦,就谷歌了下,发现了个方法,遂记录如下,方便以后查找:
方法如下
配置文件结构
publicclassDemoSettings
{
publicstringMainDomain{get;set;}
publicstringSiteName{get;set;}
}
appsettings.json中显示效果
appsettings.json
{
"DemoSettings":{
"MainDomain":"http://www.mysite.com",
"SiteName":"MyMainSite"
},
"Logging":{
"IncludeScopes":false,
"LogLevel":{
"Default":"Debug",
"System":"Information",
"Microsoft":"Information"
}
}
}
配置Services
原配置
publicvoidConfigureServices(IServiceCollectionservices)
{
//Addframeworkservices.
services.AddMvc();
}
自定义
publicvoidConfigureServices(IServiceCollectionservices)
{
//Addframeworkservices.
services.AddMvc();
//Added-usesIOptionsforyoursettings.
services.AddOptions();
//Added-ConfirmsthatwehaveahomeforourDemoSettings
services.Configure(Configuration.GetSection("DemoSettings"));
}
然后把设置注入进相应的Controller后就可以使用了
publicclassHomeController:Controller
{
privateDemoSettingsConfigSettings{get;set;}
publicHomeController(IOptionssettings)
{
ConfigSettings=settings.Value;
}
publicIActionResultIndex()
{
ViewData["SiteName"]=ConfigSettings.SiteName;
returnView();
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。