using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.json;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
namespace Common
{
/// <summary>
/// 配置文件帮助类
/// </summary>
public class ConfigHelper
{
private static readonly IConfigurationRoot Configuration;
/// <summary>
/// 静态构造方法
/// </summary>
static ConfigHelper()
{
Configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
}
/// <summary>
/// 获取配置信息
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">名字</param>
/// <param name="defaultValue">值</param>
/// <returns></returns>
public static T GetConfig<T>(string key, T defaultValue)
{
try
{
var result = Configuration[key];
return (T)Convert.ChangeType(result, typeof(T));
}
catch (Exception)
{
if (defaultValue != null)
{
return defaultValue;
}
return default(T);
}
}
/// <summary>
/// 得到配置信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T GetConfig<T>(string key)
{
try
{
var result = Configuration[key];
return (T)Convert.ChangeType(result, typeof(T));
}
catch (Exception)
{
throw new Exception(string.Format("没有在配置文件中的appSettings中找到{0}的配置,请检查配置文件配置!", key));
}
}
}
}