【问题标题】:.NET Core 3.1 loading config from appsettings.json for console application.NET Core 3.1 从 appsettings.json 为控制台应用程序加载配置
【发布时间】:2020-07-14 14:03:04
【问题描述】:

对于 .NET Core 3.1,控制台应用程序如何从 appsetting.json 文件中读取复杂对象并将其转换为相应的对象?

我在网上看到的所有示例似乎都是针对以前版本的 .NET core 的,从那时起情况似乎发生了变化。下面是我的示例代码。我真的不知道如何从这里开始。谢谢您的帮助。

appsettings.json

{
  "Player": {
    "Name": "Messi",
    "Age": "31",
    "Hobby": "Football"
  }
}

播放器.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");
}

【问题讨论】:

    标签: c# .net .net-core console .net-core-3.1


    【解决方案1】:

    在 .Net Core 3.1 中,您需要安装这些包:

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

    参考Configuration in ASP.NET Core

    【讨论】:

    • 啊,是的,很好。这给了我想要的东西。谢谢! ``` IConfigurationSection playerSection = configuration.GetSection(nameof(Player)); var name = playerSection["Name"]; ```
    • @stuck_inside_task 很高兴我能帮助你:) 祝你好运
    • 有关信息,通过 nuget 添加 Microsoft.Extensions.Configuration.Json 还将添加 Microsoft.Extensions.Configuration.FileExtensions
    • 另外值得一提的是,您应该为新添加的 appsettings.json 文件设置 Copy to Output Directory=Copy always
    猜你喜欢
    • 2023-04-10
    • 2016-12-07
    • 2016-11-02
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 2016-12-13
    相关资源
    最近更新 更多