1、添加引用Microsoft.Extensions.Configuration.Json
添加引用 Microsoft.Extensions.Configuration.Json
,引用方法可以参考:
1)使用Nuget界面管理器
搜索 "Microsoft.Extensions.Configuration.Json" 在列表中分别找到它,点击"安装"
相关文档:VS(Visual Studio)中Nuget的使用
2)使用Package Manager命令安装
PM > Install-Package Microsoft.Extensions.Configuration.Json
3)使用.NET CLI命令安装
> dotnet add package Microsoft.Extensions.Configuration.Json
2、使用ConfigurationBuilder读取appsettings.json
1)appsettings.json内容
{
"ConnectionString": "Server=localhost;Database=tempDB;Uid=<dbUserName>;Pwd=<dbPassword>",
"Smtp": {
"Host": "smtp.gmail.com",
"From": "Levi"
},
"settings": {
"From": "url@gmail.com",
"SmtpServer": "smtp.gmail.com",
"Port": 465,
"Username": "url@gmail.com",
"Password": "123456"
}
}
2)实现代码
var configuration = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json");
var config = configuration.Build();
var connectionString = config.GetConnectionString("ConnectionString");
3、获取IConfiguration的实例来读取appsettings.json
1)appsettings.json内容
{
"ConnectionStrings": {
"mysql": "Server=localhost;Database=MyDatabase;Trusted_Connection=True",
"sqlserver":"Server=localhost;Database=MyDatabase;Trusted_Connection=True"
},
"settings": {
"From": "url@gmail.com",
"SmtpServer": "smtp.gmail.com",
"Port": 465,
"Username": "url@gmail.com",
"Password": "123456"
}
}
2)实现代码
using IHost host = Host.CreateDefaultBuilder(args).Build();
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
//一种方法
string con= config.GetValue<string>("ConnectionStrings:mysql");
//另一种方法
string connectionString = config["ConnectionStrings:sqlserver"];
Console.WriteLine($"Hello, World! {connectionString}");
相关文档:ASP.NET Core 6(.NET 6) Program.cs中使用读取appsettings.json配置文件