NetCore 操作配置文件

默认配置 appsettings.json

环境配置 launchSettings.json,即开发时运行配置

 

添加依赖

Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Binder
Install-Package Microsoft.Extensions.Configuration.Json

 

 获取默认配置

string sqlConn = builder.Configuration.GetConnectionString("Default")

 如:配置数据库连接字符串

builder.Services.AddDbContext<Service.DataContext>(opt => {
    opt.UseSqlServer(builder.Configuration.GetConnectionString("Default"));
});

 

添加自定义JSON配置文件

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.Sources.Clear();
    config.AddJsonFile("redis.json", optional: false, reloadOnChange: true);
});

 

配置文件帮助类
/// <summary>
/// 读取配置文件帮助类
/// 注册服务: builder.Services.AddSingleton(new AppSettings());
/// 使用示例:
/// string data = AppSettings.ReadString(key);
/// DataConfig dataConfig = AppSettings.ReadObject<DataConfig>(key);
/// </summary>
public class AppSettings
{
    #region 注入参数
    /// <summary>
    /// 配置文件
    /// </summary>
    private static IConfiguration? _config;
    #endregion

    #region 构造函数
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="configuration">配置文件</param>
    public AppSettings()
    {
        _config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", true, reloadOnChange: true)
                .Build();
    }
    #endregion

    #region 静态方法
    /// <summary>
    /// 读取指定节点信息
    /// </summary>
    /// <param name="sessions">节点名称</param>
    /// <returns></returns>
    public static string ReadString(params string[] sessions)
    {
        try
        {
            if (_config != null && sessions.Any())
            {
                string? str = _config[string.Join(":", sessions)];
                if (!string.IsNullOrEmpty(str))
                {
                    return str;
                }
            }
        }
        catch
        {
            return string.Empty;
        }
        return string.Empty;
    }

    /// <summary>
    /// 读取实体信息
    /// </summary>
    /// <param name="sessions">节点名称</param>
    /// <returns></returns>
    public static T ReadObject<T>(params string[] sessions) where T : class, new()
    {
        T data = new();
        try
        {
            if (_config != null && sessions.Any())
            {
                _config.Bind(string.Join(":", sessions), data);
            }
        }
        catch
        {
            return data;
        }
        return data;
    }

    /// <summary>
    /// 读取实体数组信息
    /// </summary>
    /// <param name="sessions">节点名称</param>
    /// <returns></returns>
    public static List<T> ReadList<T>(params string[] sessions) where T : class
    {
        List<T> list = new();
        try
        {
            if (_config != null && sessions.Any())
            {
                _config.Bind(string.Join(":", sessions), list);
            }
        }
        catch
        {
            return list;
        }
        return list;
    }
    #endregion
}

 注册服务

// 配置文件,放在第一句,并注册为Singleton
builder.Services.AddSingleton(new AppSettings());

 使用示例

string data = AppSettings.ReadString("key");
DataConfig dataConfig = AppSettings.ReadObject<DataConfig>("key");

 

posted @ 2024-01-05 10:50  microsoft-zhcn  阅读(57)  评论(0编辑  收藏  举报