【问题标题】:Creating and reading from appconfig.json从 appconfig.json 创建和读取
【发布时间】:2022-06-22 23:27:26
【问题描述】:

我正在尝试创建包含服务器列表的配置,带有额外的值,例如

"Servers": [
{
  "Name": ".",
  "Type": "A"
},
{
  "Name": "Fred",
  "Type":  "B"
}
]

这是构建配置文件的正确方法吗?

然后我无法根据上述设置找到从配置中读取的方法。

var test = Configuration.GetSection("Servers").GetChildren();

        //List<Server> Servers = new List<Server>();
        foreach (var testItem in test)
        {
            Server server = new Server()
            {
                //Name = testItem.GetValue(,"Name"),
                //Type = testItem.GetValue("Type")
            };
            Servers.Add(server);
        }

我希望能提供一些关于如何设置配置以及如何读取这些值的指导。

感谢阅读

【问题讨论】:

标签: c# webapi appsettings


【解决方案1】:

试试这个

List<Server> servers = configuration.GetSection("Servers").Get<List<Server>>();
 
public class Server
{
    public string Name {get; set;}
    public string Type {get; set;}
}

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 2022-12-02
相关资源
最近更新 更多