在这篇文章中,我们将了解如何在 .NET Core 控制台应用程序中添加和读取 appsettings.json 文件。
我们打开 Visual Studio 并创建一个名为“ TestJson ”的控制台应用程序 (.NET Core) 项目:
现在,我们添加一个名为“Parameters.json”的文件,我们将在其中存储一个 DB 的连接字符串和两个名为 ValueABC 和 ValueDEF 的参数:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DbConnection": "ExampleTestConnection"
},
"Parameter": {
"ValueABC": "TestValue_ABC",
"ValueDEF": "TestValue_DEF"
}
}
重要提示:我们必须将文件的属性“复制到输出目录”设置为:“如果较新则复制”:
现在,为了读取 Parameters.json 文件,我们必须使用 NuGet 包添加三个库:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
最后,我们修改 Program.cs 以读取 appsetting 文件:
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
namespace TestJson
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting reading file .json");
Console.WriteLine($"ConnectioString: {GetDbConnection()}");
Console.WriteLine($"The parameters are: {GetParameters()}");
Console.ReadLine();
}
private static string GetDbConnection()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("Parameters.json", optional: true, reloadOnChange: true);
string strConnection = builder.Build().GetConnectionString("DbConnection");
return strConnection;
}
private static string GetParameters()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("Parameters.json", optional: true, reloadOnChange: true);
var val1 = builder.Build().GetSection("Parameter").GetSection("ValueABC").Value;
var val2 = builder.Build().GetSection("Parameter").GetSection("ValueDEF").Value;
return $"The values of parameters are: {val1} and {val2}";
}
}
}
如果我们运行应用程序,这将是结果:



