120 lines
3.7 KiB
C#
120 lines
3.7 KiB
C#
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
|
||
{
|
||
/// <summary>
|
||
/// 缓存配置文件
|
||
/// </summary>
|
||
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);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 缓存配置文件创建时间
|
||
/// </summary>
|
||
static DateTime createTime;
|
||
|
||
/// <summary>
|
||
/// 缓存配置文件失效时间
|
||
/// </summary>
|
||
static DateTime validTime;
|
||
|
||
/// <summary>
|
||
/// 获取配置信息(必项)
|
||
/// </summary>
|
||
/// <param name="sections"></param>
|
||
/// <returns>当不存在或为空是输出异常</returns>
|
||
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);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取配置文件
|
||
/// </summary>
|
||
/// <param name="sections"></param>
|
||
/// <param name="defaultValue">默认返回值</param>
|
||
/// <returns>当不存在的配置项会返回null</returns>
|
||
/// <remarks>
|
||
/// 获取实例:
|
||
/// BaseConfig.App(new string[] { "Logging" });
|
||
/// BaseConfig.App(new string[] { "Logging", "LogLevel" });
|
||
/// </remarks>
|
||
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;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 递归获取配置信息数组
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="sections"></param>
|
||
/// <returns></returns>
|
||
public static List<T> App<T>(params string[] sections)
|
||
{
|
||
List<T> list = new List<T>();
|
||
configuration.Bind(string.Join(":", sections), list);
|
||
return list;
|
||
}
|
||
}
|
||
}
|