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

  在.NET Framework框架时代我们的应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别用

System.Configuration.ConfigurationManager.AppSettings["SystemName"];//读取appSettings配置
System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionStr"];//读取connectionStrings配置

读取配置文件和数据库链接。

  

  现在我们终于迎来.NET Core时代,越来越多的应用被迁移至.NET Core框架下,.NET Core2.0发布以后,.NET Core更加成熟了,原本在.NET Framework框才有的类库.NET Core也基本全部实现,并有增强。因此小菜我也已经准备好加入.NET Core大军中,所以小菜我最近开始修炼.NET Core大法。

  

  欲铸剑,必先打铁,我要一步步来,读取配置文件是一个应用中必不可少的,先弄清怎么读取配置文件,.NET Core配置文件为appsettings.json,为了满足在各个不同类中都能便捷的读取appsettings.json中的配置,所以我需要将读取appsettings.json封装到类库中。在Startup中读取就不说了,在类库中实现读取怎么玩儿?直接上代码,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"
}

建一个项目名称为NetCoreOrder.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 })
            //根据环境变量读取配置
            //Add(new JsonConfigurationSource { Path = $"appsettings.{System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", ReloadOnChange = true })
            .Build();
        }
        /// <summary> 
        /// 通过强类型绑定读取配置 
        /// </summary> 
        /// <typeparam name="Entity">要绑定的类型</typeparam> 
        /// <param name="keyPath">配置文件路径</param> 
        /// <returns>绑定的类</returns> 
        public static Entity GetSectionObject<Entity>(string keyPath = null) where Entity : new()
        {
            var entity = new Entity();
            if (string.IsNullOrEmpty(keyPath))
            {
                //将appsettings.json全部配置绑定到模型  
                Configuration.Bind(entity);
            }
            else
            {
                //将指定路径下的配置项绑定到模型 
                var section = Configuration.GetSection(keyPath);
                section.Bind(entity);
            }
            return entity;
        }
    }
}

A.读取配置文件的代码完成了,只要引用了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

B.通过强类型读取Appsettings节点的配置值

增加模型类

public class Appsettings
{
  public string SystemName { get; set; }
  public DateTime Date { get; set; }
  public string Author { get; set; }
}

public class ConnectionStrings
{
  public string CxyOrder { get; set; }
}

public class AppsettingConfig
{
  public ConnectionStrings ConnectionStrings { get; set; }

  public Appsettings Appsettings { get; set; }

  public string ServiceUrl { get; set; }
}

强类型读取配置值

using Microsoft.AspNetCore.Mvc;
using NetCore.Common;
using System;

namespace NetCore.Controllers
{
    [ApiController]
    [Route("/")]
    public class HelloNetCoreController : ControllerBase
    {

        [HttpGet("/getconfig")]
        public ActionResult GetConfig()
        {
            //读取Appsettings节点配置
            var config = AppConfigurtaionServices.GetSectionObject<Appsettings>("Appsettings");
            return new JsonResult(config);
            //返回:{"systemName":"PDF .NET CORE","date":"2017-07-23T00:00:00","author":"PDF"}
        }

        [HttpGet("/getAllConfig")]
        public ActionResult GetAllConfig()
        {
            //读取整个配置文件的配置
            var config = AppConfigurtaionServices.GetSectionObject<AppsettingConfig>();
            return new JsonResult(config);
            //返回:{"connectionStrings":{"cxyOrder":"Server=LAPTOP-AQUL6MDE\\MSSQLSERVERS;Database=CxyOrder;User ID=sa;Password=123456;Trusted_Connection=False;"},"appsettings":{"systemName":"PDF .NET CORE","date":"2017-07-23T00:00:00","author":"PDF"},"serviceUrl":"https://www.baidu.com/getnews"}
        }
    }
}

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

小菜笔记,若有不妥,望指正!

原文地址:https://www.cnblogs.com/pudefu/p/7580722.html