using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Appointment.Entity { public class BaseConfig { /// /// 缓存配置文件 /// static IConfiguration configuration { get; set; } static BaseConfig() { /* 当配置文件更新后,IConfiguration会自动更新,使用缓存为了双重保障 */ DateTime now = DateTime.Now; if (validTime < now) { string path = "appsettings.json"; var _newCreateTime = System.IO.File.GetCreationTime(path); if (_newCreateTime != createTime) { configuration = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = path, Optional = false, ReloadOnChange = true }).Build(); createTime = _newCreateTime; } validTime = now.AddSeconds(60); } } /// /// 缓存配置文件创建时间 /// static DateTime createTime; /// /// 缓存配置文件失效时间 /// static DateTime validTime; /// /// 获取配置信息(必项) /// /// /// 当不存在或为空是输出异常 public static string App(params string[] sections) { try { if (sections.Any()) { string str = configuration[string.Join(":", sections)]; if (!string.IsNullOrEmpty(str)) { return str; } } throw new Exception($"没有在配置文件中的appSettings中找到{sections.Last()}的配置,请检查配置文件配置!"); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 获取配置文件 /// /// /// 默认返回值 /// 当不存在的配置项会返回null /// /// 获取实例: /// BaseConfig.App(new string[] { "Logging" }); /// BaseConfig.App(new string[] { "Logging", "LogLevel" }); /// public static string App(string[] sections, string defaultValue) { try { if (sections.Any()) { string stre = configuration[string.Join(":", sections)]; if (!string.IsNullOrEmpty(stre)) return stre; } return defaultValue; } catch (Exception) { return defaultValue; } } /// /// 递归获取配置信息数组 /// /// /// /// public static List App(params string[] sections) { List list = new List(); configuration.Bind(string.Join(":", sections), list); return list; } } }