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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

andy-zl   2021-03-24 我要评论
想了解ASP.NET core Web中使用appsettings.json配置文件的方法的相关内容吗,andy-zl在本文为您仔细讲解ASP.NET core Web用appsettings.json配置文件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:asp.net,core配置文件,appsettings.json,asp.net,core,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();
 }
}

总结

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们