在.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 }) .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文件上右鍵——屬性——將“復制到輸出目錄”項的值改為“始終復制”即可。
小菜筆記,若有不妥,望指正!
