appsettings.json数据读取辅助类

配置文件

{
  "IdentityServer": {
    "Authority": "http://localhost:8501",
    "ApiName": "net7_microservice"
  },
  "Service": {
    "IP": "localhost",
    "Port": "8503",
    "Name": "NET7Service"
  },
  "Consul": {
    "IP": "localhost",
    "Port": "8500"
  }
}

工具类:AppSettingsHelper


/// <summary>
/// 配置帮助类
/// </summary>
public class AppSettingsHelper
{
    static IConfiguration _config;
    public AppSettingsHelper(IConfiguration configuration)
    {
        _config = configuration;
    }
    /// <summary>
    /// 获取键的值
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="IsConn">是否为数据库连接字符串</param>
    /// <returns></returns>
    public static string Get(string key, bool IsConn = false)
    {
        string value;
        try
        {
            if (key.IsNull()) return null;
            if (IsConn)
            {
                value = _config.GetConnectionString(key);
            }
            else
            {
                value = _config[key];
            }
        }
        catch (Exception)
        {
            value = null;
        }
        return value;
    }
    public static string Get(params string[] sessions)
    {
        try
        {
            if (sessions.Any())
            {
                return _config[string.Join(":", sessions)];
            }
        }
        catch
        {
            return null;
        }
        return null;
    }
    public static string Get(string key)
    {
        try
        {
            if (key.IsNull()) return null;
            return _config[key];
        }
        catch
        {
            return null;
        }
    }
    public static List<T> Get<T>(params string[] session)
    {
        var list = new List<T>();
        _config.Bind(string.Join(":", session), list);
        return list;
    }
    public static IConfigurationSection GetSection(string key)
    {
        try
        {
            return _config.GetSection(key);
        }
        catch
        {
            return null;
        }
    }
}

注册:Program.cs文件的最上方添加如下代码:


var builder = WebApplication.CreateBuilder(args);
var basePath = AppContext.BaseDirectory;

#region 引入配置文件
var _config = new ConfigurationBuilder()
                 .SetBasePath(basePath)
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 .Build();
builder.Services.AddSingleton(new AppSettingsHelper(_config));
#endregion

用法:


AppSettingsHelper.Get("IdentityServer:ApiName");

1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值