.NET Core 3.1从appsettings.json加载配置以用于控制台应用程序 [英] .NET Core 3.1 loading config from appsettings.json for console application

查看:61
本文介绍了.NET Core 3.1从appsettings.json加载配置以用于控制台应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于.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

Player.cs

class Player
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string Hobby { get; set; }
}

Program.cs

Program.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));
}

参考 ASP.NET Core中的配置

这篇关于.NET Core 3.1从appsettings.json加载配置以用于控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆