.NET Core中读取json配置文件
.NET Core配置文件为appsettings.json,为了满足在各个不同类中都能便捷的读取appsettings.json中的配置,所以我需要将读取appsettings.json封装到类库中。在Startup中读取就不说了,appsettings.json文件内容如下:
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "TestConnection": "Server=.;Database=OWNDB;User ID=sa;Password=123456;Trusted_Connection=False;" }, "Appsettings": { "SystemName": "PDF .NET CORE", "Date": "2017-07-23", "Author": "PDF" }, "ServiceUrl": "http://www.cnblogs.com/chuankang/" }
建一个项目名称为NetCore.Common的类库项目,并给该类库项目引入 Microsoft.Extensions.Configuration 和 Microsoft.Extensions.Configuration.Json程序包,类库中加载appsettings.json配置文件代码如下:
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; namespace NetCore.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(); } } }
读取配置文件的代码完成了,只要引用了NetCore.Common类库的项目中都能方便读取数据库链接字符串和其他配置,使用方法如下:
AppConfigurtaionServices.Configuration.GetConnectionString("TestConnection"); //得到 Server=.;Database=OWNDB;User ID=sa;Password=123456;Trusted_Connection=False;
读取一级配置节点配置
AppConfigurtaionServices.Configuration["ServiceUrl"]; //得到 http://www.cnblogs.com/chuankang/
读取二级子节点配置
AppConfigurtaionServices.Configuration["Appsettings:SystemName"]; //得到 PDF .NET CORE AppConfigurtaionServices.Configuration["Appsettings:Author"]; //得到 PDF
注意,如果AppConfigurtaionServices类中抛出FileNotFoundException异常,说明目录下未找到appsettings.json文件,这时请在项目appsettings.json文件上右键——属性——将“复制到输出目录”项的值改为“如果较新则复制”即可。