欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.NET Core在类库中读取配置文件appsettings.json

程序员文章站 2024-01-04 15:50:22
...

直接上代码,appsettings.json文件内容如下:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "CxyOrder": "Server=LAPTOP-AQUL6MDE\\MSSQLSERVERS;Database=CxyOrder;User ID=sa;Password=123456;Trusted_Connection=False;"
  },
  "Appsettings": {
    "SystemName": "PDF .NET CORE",
    "Date": "2017-07-23",
    "Author": "PDF"
  },
  "ServiceUrl": "https://www.baidu.com/getnews"
}

建一个项目名称为Common的类库项目,并给该类库项目引入 Microsoft.Extensions.Configuration 和 Microsoft.Extensions.Configuration.Json程序包,类库中加载appsettings.json配置文件代码如下:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace Common
{
    /// <summary>
    /// 读取配置文件
    /// </summary>
    public class AppConfigurtaionServices
    {
        public static IConfiguration Configuration { get; set; }
        static AppConfigurtaionServices()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载            
            Configuration = new ConfigurationBuilder()
              .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
              .Build();            
        }
    }
}

读取配置文件的代码完成了,只要引用了NetCoreOrder.Common类库的项目中都能方便读取数据库链接字符串和其他配置,使用方法如下:

AppConfigurtaionServices.Configuration.GetConnectionString("CxyOrder"); 
//得到 Server=LAPTOP-AQUL6MDE\\MSSQLSERVERS;Database=CxyOrder;User ID=sa;Password=123456;Trusted_Connection=False;

读取一级配置节点配置

AppConfigurtaionServices.Configuration["ServiceUrl"];
//得到 https://www.baidu.com/getnews

读取二级子节点配置

AppConfigurtaionServices.Configuration["Appsettings:SystemName"];
//得到 PDF .NET CORE
AppConfigurtaionServices.Configuration["Appsettings:Author"];
//得到 PDF

注意,如果AppConfigurtaionServices类中抛出FileNotFoundException异常,说明目录下未找到appsettings.json文件,这时请在项目appsettings.json文件上右键——属性——将“复制到输出目录”项的值改为“始终复制”即可。

相关标签: .net core

上一篇:

下一篇: