.NET Core 3.1 loading config from appsettings.json for console application

荒凉一梦 提交于 2021-01-02 06:15:42

问题


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?

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

{
  "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; }
}

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");
}

回答1:


In .Net Core 3.1 you need to install these packages:

  • Microsoft.Extensions.Configuration.Json

  • Microsoft.Extensions.Configuration.FileExtensions

then build IConfiguration:

 static void Main(string[] args)
 {
    IConfiguration configuration = new ConfigurationBuilder()
       .AddJsonFile("appsettings.json", true,true)
       .Build();
    var playerSection = configuration.GetSection(nameof(Player));
}

Reference Configuration in ASP.NET Core



来源:https://stackoverflow.com/questions/60994309/net-core-3-1-loading-config-from-appsettings-json-for-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!