• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
我只吃饭不洗碗
博客园    首页    新随笔    联系   管理    订阅  订阅
.net core 读取appsetting.json 封装
/* 需要引入的包
Microsoft.Extensions.Configuration - 提供配置的核心功能。
Microsoft.Extensions.Configuration.Json - 支持从 JSON 文件加载配置。
Microsoft.Extensions.Configuration.FileExtensions - 支持文件相关的配置,如设置基路径。
Microsoft.Extensions.Configuration.Binder
 */
/// <summary>
/// 作者:我只吃饭不洗碗
/// AppSettings读取配置类。
/// </summary>
public static class AppSettingsConsole
{
    /// <summary>
    /// 获取指定键的值。
    /// </summary>
    /// <param name="key">要获取值的键。</param>
    /// <returns>指定键的值。</returns>
    public static string GetValue(string key)
    {
        var appsettingsPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
        IConfiguration config = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile(appsettingsPath, optional: true, reloadOnChange: true)
            .Build();
        return config.GetValue<string>(key);
    }
}

调用示例:

var operation= AppSettingsConsole.GetValue("Operation") ;//只能读取string 类型,若读取其他类型的配置,请自行修改GetValue方法
//这是json的配置

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Operation": "CoaTemplate"
}

 

posted on 2024-02-22 09:56  我只吃饭不洗碗  阅读(170)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3