引用nuget
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.EnvironmentVariables
Microsoft.Extensions.Configuration.Json
using Allspark.Core.Common.Json;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
namespace Allspark.Core.Common.Config
{
public static class Configs
{
private const string DefaultConfigName = "appsettings.json";
public class ConfigCache
{
internal static readonly IConfigurationRoot ConfigRoot = null;
static ConfigCache()
{
try
{
string pathToContentRoot = Directory.GetCurrentDirectory();
string configFilePath = Path.Combine(pathToContentRoot, DefaultConfigName);
if (!File.Exists(configFilePath))
{
throw new FileNotFoundException($"{DefaultConfigName}配置文件不存在!");
}
//用于构建基于键/值的配置设置,以便在应用程序中使用
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(pathToContentRoot)//将基于文件的提供程序的FileProvider设置为PhysicalFileProvider基本路径
.AddJsonFile(DefaultConfigName, optional: false, reloadOnChange: true)//在构建器的路径中添加JSON配置提供程序
.AddEnvironmentVariables();//添加读取的Microsoft.Extensions.Configuration.IConfigurationProvider来自环境变量的配置值
ConfigRoot = builder.Build();
}
catch (Exception)
{
}
finally
{
}
}
}
/// <summary>
/// 根据名称读取指定配置文件。若无法读取到数据,则使用defaultValue的值
/// </summary>
/// <typeparam name="T">节点的类型,可传对象</typeparam>
/// <param name="name">配置文件节点名</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static T Get<T>(string name, T defaultValue)
{
if (ConfigCache.ConfigRoot == null)
{
// throw new NullReferenceException("配置文件加载异常!");
return defaultValue;
}
IConfigurationSection section = ConfigCache.ConfigRoot.GetSection(name);
if (section == null)
{
throw new KeyNotFoundException($"{name}节点不存在!");
}
var config = section.Get<T>();
if (config == null)
return defaultValue;
return config;
}
/// <summary>
/// 根据名称读取指定配置文件
/// </summary>
/// <typeparam name="T">节点的类型,可传对象</typeparam>
/// <param name="name">配置文件节点名</param>
/// <returns></returns>
public static T Get<T>(string name)
{
return Get<T>(name, default);
}
public static string Set<T>(string key, T value)
{
string StrValue = JsonHelper.ObjectToJson(value);
IEnumerable<IConfigurationProvider> configProviders = ConfigCache.ConfigRoot.Providers;
foreach (IConfigurationProvider item in configProviders)
{
if (item.TryGet(key, out string itemValue))
{
item.Set(key, StrValue);
return StrValue;
}
}
return "";
}
}
}