.NET Core 3.1 从 appsettings.json 为控制台应用程序加载配置 [英] .NET Core 3.1 loading config from appsettings.json for console application
问题描述
对于 .NET Core 3.1,控制台应用程序如何从 appsetting.json 文件中读取复杂对象并将其转换为相应的对象?
For .NET Core 3.1, console application how can I read a complex object from appsetting.json file and cast it into the corresponding object?
我在网上看到的所有示例似乎都是针对以前版本的 .NET core 的,从那时起事情似乎发生了变化.下面是我的示例代码.我真的不知道如何从这里开始.感谢您的帮助.
All the examples I see online seem to be for previous versions of .NET core and things seems to have changed since then. Below is my sample code. I don't really know how to proceed from here. Thank you for your help.
appsettings.json
appsettings.json
{
"Player": {
"Name": "Messi",
"Age": "31",
"Hobby": "Football"
}
}
Player.cs
class Player
{
public string Name { get; set; }
public string Age { get; set; }
public string Hobby { get; set; }
}
程序.cs
static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location))
.AddJsonFile("appsetting.json").Build();
var playerSection = config.GetSection("Player");
}
推荐答案
在 .Net Core 3.1 中你需要安装这些包:
In .Net Core 3.1 you need to install these packages:
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.FileExtensions
然后构建IConfiguration
:
static void Main(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true,true)
.Build();
var playerSection = configuration.GetSection(nameof(Player));
}
这篇关于.NET Core 3.1 从 appsettings.json 为控制台应用程序加载配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!