当前位置: 首页 > news >正文

netframework 读取appsettings.json

AppSettingsHelper:

using Newtonsoft.Json.Linq;
using System;
using System.IO;

public class AppSettingsHelper
{
    private static JObject _appSettings;

    static AppSettingsHelper()
    {
        try
        {
            // 获取 appsettings.json 文件的路径
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
            // 检查文件是否存在
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("appsettings.json file not found!");
            }

            // 读取文件内容并解析为 JObject
            var json = File.ReadAllText(filePath);
            _appSettings = JObject.Parse(json);
        }
        catch (Exception ex)
        {
            throw new Exception($"Error loading appsettings.json: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取指定键的值
    /// </summary>
    /// <param name="keyPath">键路径,例如 "AppSettings:Setting1"</param>
    /// <param name="defaultValue">默认值(可选)</param>
    /// <returns>键对应的值,如果键不存在则返回默认值</returns>
    public static string GetSetting(string keyPath, string defaultValue = null)
    {
        if (_appSettings == null)
        {
            throw new Exception("appsettings.json is not loaded.");
        }

        // 分割键路径
        var keys = keyPath.Split(':');
        JToken token = _appSettings;

        // 逐级查找键
        foreach (var key in keys)
        {
            token = token[key];
            if (token == null)
            {
                throw new Exception($"Key '{key}' in path '{keyPath}' not found.");
            }
        }
        return token.ToString();
    }

    /// <summary>
    /// 获取指定键的值并转换为指定类型
    /// </summary>
    /// <typeparam name="T">目标类型</typeparam>
    /// <param name="keyPath">键路径,例如 "AppSettings:Setting1"</param>
    /// <param name="defaultValue">默认值(可选)</param>
    /// <returns>键对应的值,如果键不存在则返回默认值</returns>
    public static T GetSetting<T>(string keyPath, T defaultValue = default)
    {
        if (_appSettings == null)
        {
            throw new Exception("appsettings.json is not loaded.");
        }

        // 分割键路径
        var keys = keyPath.Split(':');
        JToken token = _appSettings;

        // 逐级查找键
        foreach (var key in keys)
        {
            token = token[key];
            if (token == null)
            {
                throw new Exception($"Key '{key}' in path '{keyPath}' not found.");
            }
        }
        return token.ToObject<T>();
    }
}

appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
  },
  "AppSettings": {
    "Setting1": "Value1",
    "Setting2": "Value2"
  }
}

output:

 class Program
 {
     static void Main(string[] args)
     {
         // 读取字符串类型的配置
         var setting1 = AppSettingsHelper.GetSetting("AppSettings:Setting1");
         Console.WriteLine($"Setting1: {setting1}");

         // 读取连接字符串
         var connectionString = AppSettingsHelper.GetSetting("ConnectionStrings:DefaultConnection");
         Console.WriteLine($"DefaultConnection: {connectionString}");

         // 读取并转换为特定类型(如果需要)
         var setting2 = AppSettingsHelper.GetSetting<string>("AppSettings:Setting2");
         Console.WriteLine($"Setting2: {setting2}");

         Console.ReadKey();
     }
 }

相关文章:

  • 【Redis】常用命令汇总
  • RMSNorm模块
  • SQL-labs13-16闯关记录
  • LeetCode-Hot100-008无重复最长子串
  • 111. 二叉树的最小深度
  • ESP32之Flash操作
  • 数字人分身/123数字人/数字人直播
  • [51 单片机] --串口编程
  • 【华为OD机考】华为OD笔试真题解析(17)--打印文件
  • 2025-03-04 学习记录--C/C++-PTA 习题5-4 使用函数求素数和
  • 手动调整3DTiles倾斜模型的高度、位置、亮度
  • MWC 2025 | 紫光展锐联合移远通信推出全面支持R16特性的5G模组RG620UA-EU
  • HTML label 标签使用
  • 基于微信小程序的心理健康恢复系统+LW示例参考
  • 用DeepSeeker写小说构思 《故事大纲、主线、剧情风格》
  • 无人机遥控器无线传输技术解析!
  • 如何在随机振动分析中包括缓冲器
  • 【MySQL】与MongoDB的区别,字符集,三范式,存储引擎InnoDB、MyISAM
  • 【C++设计模式】第三篇:抽象工厂模式(Abstract Factory)
  • MySQL JOIN 与子查询深度对比:原理、性能陷阱与优化策略
  • 样本代替做网站/最近几天的新闻大事
  • 一般做网站的在哪里找/网络seo推广培训
  • wordpress建什么站/seo白帽优化
  • 大庆开发网站公司/百度推广一个月多少钱
  • wordpress网站邀请码/海外网络推广服务
  • 网站建设基本内容/开封网站设计