前言
最近在研究把asp.net程序移植到linux上,正好.net core出来了,就进行了学习。
移植代码基本顺利,但是发现.net core中没有ConfigurationManager,无法读写配置文件,单独写个xml之类的嫌麻烦,就谷歌了下,发现了个方法,遂记录如下,方便以后查找:
方法如下
配置文件结构
public class DemoSettings
{
public string MainDomain { get; set; }
public string SiteName { 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
原配置
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
自定义
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// Added - uses IOptions<T> for your settings.
services.AddOptions();
// Added - Confirms that we have a home for our DemoSettings
services.Configure<DemoSettings>(Configuration.GetSection("DemoSettings"));
}
然后把设置注入进相应的Controller后就可以使用了
public class HomeController : Controller
{
private DemoSettings ConfigSettings { get; set; }
public HomeController(IOptions<DemoSettings> settings)
{
ConfigSettings = settings.Value;
}
public IActionResult Index()
{
ViewData["SiteName"] = ConfigSettings.SiteName;
return View();
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
桃源资源网 Design By www.nqtax.com
暂无“ASP.NET core Web中使用appsettings.json配置文件的方法”评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。