服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - ASP.NET core Web中使用appsettings.json配置文件的方法

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

2020-05-01 15:35andy-zl ASP.NET教程

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

前言

最近在研究把asp.net程序移植到linux上,正好.net core出来了,就进行了学习。

移植代码基本顺利,但是发现.net core中没有ConfigurationManager,无法读写配置文件,单独写个xml之类的嫌麻烦,就谷歌了下,发现了个方法,遂记录如下,方便以后查找:

方法如下

配置文件结构

?
1
2
3
4
5
public class DemoSettings
{
 public string MainDomain { get; set; }
 public string SiteName { get; set; }
}

appsettings.json中显示效果

appsettings.json

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
 "DemoSettings": {
 "MainDomain": "http://www.mysite.com",
 "SiteName": "My Main Site"
 },
 "Logging": {
 "IncludeScopes": false,
 "LogLevel": {
  "Default": "Debug",
  "System": "Information",
  "Microsoft": "Information"
 }
 }
}

配置Services

原配置

?
1
2
3
4
5
public void ConfigureServices(IServiceCollection services)
{
 // Add framework services.
 services.AddMvc();
}

自定义

?
1
2
3
4
5
6
7
8
9
10
11
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后就可以使用了

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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();
 }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://metroset.me/?p=80

延伸 · 阅读

精彩推荐