using Microsoft.Extensions.Configuration.Json;
|
using Microsoft.Extensions.Configuration;
|
using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace WIDESEA_Core.Helper
|
{
|
/// <summary>
|
/// appsettings.json操作类
|
/// </summary>
|
public class AppSettings
|
{
|
// 定义一个静态的 IConfiguration 对象
|
public static IConfiguration Configuration { get; set; }
|
// 定义一个静态的 string 对象
|
static string contentPath { get; set; }
|
|
// 构造函数,传入 contentPath 参数
|
public AppSettings(string contentPath)
|
{
|
string Path = "appsettings.json";
|
|
//如果你把配置文件 是 根据环境变量来分开了,可以这样写
|
//Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";
|
|
Configuration = new ConfigurationBuilder()
|
.SetBasePath(contentPath)
|
.Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//这样的话,可以直接读目录里的json文件,而不是 bin 文件夹下的,所以不用修改复制属性
|
.Build();
|
}
|
|
// 构造函数,传入 IConfiguration 参数
|
public AppSettings(IConfiguration configuration)
|
{
|
Configuration = configuration;
|
}
|
|
/// <summary>
|
/// 封装要操作的字符
|
/// </summary>
|
/// <param name="sections">节点配置</param>
|
/// <returns></returns>
|
public static string Get(params string[] sections)
|
{
|
try
|
{
|
if (sections.Any())
|
{
|
return Configuration[string.Join(":", sections)];
|
}
|
}
|
catch (Exception) { }
|
|
return "";
|
}
|
|
/// <summary>
|
/// 从配置中获取指定节点下的列表数据
|
/// </summary>
|
/// <typeparam name="T">列表元素类型</typeparam>
|
/// <param name="sections">配置节点路径参数</param>
|
/// <returns>绑定后的列表对象</returns>
|
/// <remarks>需要引用 Microsoft.Extensions.Configuration.Binder 包</remarks>
|
public static List<T> Get<T>(params string[] sections)
|
{
|
List<T> list = new List<T>();
|
// 引用 Microsoft.Extensions.Configuration.Binder 包
|
Configuration.Bind(string.Join(":", sections), list);
|
return list;
|
}
|
|
/// <summary>
|
/// 从配置中获取指定路径的值
|
/// </summary>
|
/// <param name="sectionsPath">配置项的路径</param>
|
/// <returns>返回配置值,若获取失败则返回空字符串</returns>
|
public static string GetValue(string sectionsPath)
|
{
|
try
|
{
|
return Configuration[sectionsPath];
|
}
|
catch (Exception) { }
|
|
return "";
|
|
}
|
}
|
}
|