ASP.NET core Web中如何使用appsettings.json配置文件

这篇文章主要介绍了ASP.NET core Web中如何使用appsettings.json配置文件,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

前言

最近在研究把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();
 }
}

感谢你能够认真阅读完这篇文章,希望小编分享的“ASP.NET core Web中如何使用appsettings.json配置文件”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注行业资讯频道,更多相关知识等着你来学习!