.net6.0(.net Core)读取 appsettings.json 配置文件

① 新项目中创建名为 appsettings.json 的 json文件,内容为:

cs 复制代码
{
  //数据库连接字符串:
  "ConnectionString": {
    "DBconn": "server=127.0.0.1;database=db;uid=sa;pwd=123456;Timeout=600;Encrypt=True;TrustServerCertificate=True;" //开发环境
  },
"Debug":"false" //是否调试:true调试;false不调试
}

② 创建名为 ConfigHelper.cs 的 cs文件,内容为:

cs 复制代码
using Microsoft.Extensions.Configuration;

namespace namespace.DAL
{
    public class ConfigHelper
    {
        //读取配置文件:appsettings
        //1.Microsoft.Extensions.Configuration;
        //2.Microsoft.Extensions.Configuration.Json; 
        public static string GetConfig(string key)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); //默认读取:当前运行目录
            IConfigurationRoot configuration = builder.Build();
            string configValue = configuration.GetSection(key).Value;
            return configValue;
        }
    }
}

NuGet中获取并安装,以下两个:

1.Microsoft.Extensions.Configuration;

2.Microsoft.Extensions.Configuration.Json;


③读取config文件里的配置

//读取只有一层节点的配置

bool Debug =Convert.ToBoolean(ConfigHelper.GetConfig("Debug"));//根节点

//读取两层节点的配置

string _connectionString = ConfigHelper.GetConfig("ConnectionString**:**DBconn");//根节点 : 子节点

相关推荐
hez20102 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
Venuslite4 天前
从 Unexpected token < 到 Extra data:一次讲清 JSON 解析错误的排查思路
json
唐青枫8 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫9 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
Caco_D9 天前
一行代码抓遍全网 20 个热榜!Aneiang.Pa 4.0 发布 — 极简 .NET 爬虫库
爬虫·.net
咕白m6259 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
小码编匠10 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
疯狂SQL10 天前
手写高性能在线 JSON 工具|Web Worker 工程化打包 + 语法自动修复 + 多语言代码生成实战
typescript·json·next.js·web worker·前端性能优化·esbuild·源码实战