• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

ASP.NET core Web中使用appsettings.json配置文件的方法

asp 搞代码 4年前 (2022-01-03) 20次浏览 已收录 0个评论

这篇文章主要给大家介绍了在ASP.NET core Web中使用appsettings.json配置文件的方法,文中给出了详细的示例代码,需要的朋友可以参考学习,下面来一起看看吧。

前言

最近在研究把asp.net程序移植到linux上,正好.net core出来了,来源gaodai#ma#com搞*!代#%^码网就进行了学习。

移植代码基本顺利,但是发现.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 for your settings. services.AddOptions(); // Added - Confirms that we have a home for our DemoSettings services.Configure(Configuration.GetSection("DemoSettings")); }

然后把设置注入进相应的Controller后就可以使用了

 public class HomeController : Controller { private DemoSettings ConfigSettings { get; set; } public HomeController(IOptions settings) { ConfigSettings = settings.Value; } public IActionResult Index() { ViewData["SiteName"] = ConfigSettings.SiteName; return View(); } }

总结

以上就是ASP.NET core Web中使用appsettings.json配置文件的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:ASP.NET core Web中使用appsettings.json配置文件的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址