1. 编辑项目文件
添加如下NuGet包
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0" />
2.配置文件添加
appsettings.json文件
{
"AccessKeyId": "abcdefghijklmnopqrst"
}
3.读取配置文件
在方法中添加
using Microsoft.Extensions.Configuration;
//读取配置文件
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
string AccessKeyId = config["AccessKeyId"];
string PostgreSQL= config.GetConnectionString("PostgreSQL");
扩展
static HomeClass()
{
//读取配置文件
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
RedisConnectionString = config.GetConnectionString("Redis");
}
/// <summary>
/// 配置数据库地址
/// </summary>
private static readonly string RedisConnectionString;