【www.bbyears.com--linux】
word-wrap: break-word; margin: 5px 0px; color: rgb(0, 0, 0); font-family: " sans="" font-size:="" font-style:="" font-variant-ligatures:="" a="" href="/fw/photo.html" target="_blank" :="" font-weight:="" letter-spacing:="" orphans:="" text-align:="" text-indent:="" text-transform:="" white-space:="" widows:="" word-spacing:="" -webkit-text-stroke-width:="">最近在研究把asp.net程序移植到linux上,正好.net core出来了,就进行了学习。
移植代码基本顺利,但是发现.net core中没有ConfigurationManager,无法读写配置文件,单独写个xml之类的嫌麻烦,就谷歌了下,发现了个方法,遂记录如下,方便以后查找:
方法如下
配置文件结构
代码如下
publicclassDemoSettings
{
publicstringMainDomain {get;set; }
publicstringSiteName {get;set; }
}
appsettings.json中显示效果
appsettings.json
代码如下
{
"DemoSettings": {
"MainDomain": "http://www.mysite.com",
"SiteName": "My Main Site"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
配置Services
原配置
代码如下
publicvoidConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
自定义
代码如下
publicvoidConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// Added - uses IOptions
services.AddOptions();
// Added - Confirms that we have a home for our DemoSettings
services.Configure
}
然后把设置注入进相应的Controller后就可以使用了
代码如下
publicclassHomeController : Controller
{
privateDemoSettings ConfigSettings {get;set; }
publicHomeController(IOptions
{
ConfigSettings = settings.Value;
}
publicIActionResult Index()
{
ViewData["SiteName"] = ConfigSettings.SiteName;
returnView();
}
}
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助。