① 新项目中创建名为 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");//根节点 : 子节点