在ASP.NET Core中迭代并读取所有appsettings密钥

5

我在我的 asp.net core 3.0 web api 项目的 appsettings.json 文件中添加了一些配置,文件看起来像这样:

{
  "Logging":{..},
  "AllowedHosts": "*",
  "Section1": {
     "Key1": "Value1",
     "Key2": "Value2",
     ....
  }
}

我想要遍历该特定部分“Section1”中的所有键,并对它们执行某些操作。我尝试了以下方法,但它没有起作用:

foreach (var key in ConfigurationManager.AppSettings.AllKeys)
                {
                    var key = ConfigurationManager.AppSettings["Key1"];
                    // perform some action
                }

ConfigurationManager.AppSettings在下面的屏幕截图中可以看到并没有包含任何内容:

enter image description here

要让它工作,您还需要做什么?

我尝试了var v = this._configuration.GetSection("Section1").GetSection("Key1");,其中_configurationIConfiguration类型,并且结果符合预期。但是,正如我之前提到的那样,我不想这样做,相反,我想遍历所有appsettings的键列表并对它们执行某些操作。

任何帮助都将是伟大的。


在.NET Core中没有这样的类。 - Panagiotis Kanavos
我已经尝试过使用GetSection和GetValue,它们也可以工作。但是我的要求是特别循环遍历键列表并对它们进行一些处理,而不是使用硬编码的键名检索键值,这就是使用GetSection或GetValue发生的情况。 - The Inquisitive Coder
5
顺便提一下,你可以使用AsEnumerable()来枚举所有键值对。 - Panagiotis Kanavos
@PanagiotisKanavos 我编辑了我的问题,使其更加清晰,请看一下。 - The Inquisitive Coder
@PanagiotisKanavos 是的,这个 this._configuration.GetSection("Section1").AsEnumerable(); 确实可以工作,尽管它给出的第一个值必须被忽略,因为它是一个空值;否则它基本上满足了我的要求!谢谢! - The Inquisitive Coder
显示剩余4条评论
4个回答

2
我试了Brandon的答案,但遇到了困难。这是我想出来的解决办法:
public static void DoSomethingWithConfigurationManager(IConfigurationRoot config)
{
    var section = config.GetSection("exampleSection").GetChildren();
    foreach (var item in section)
    {
        // Do something with item.Key and item.Value
        // You can access lower sections with item.GetChildren() and repeat the process
    }
}

1

像这样,您可以遍历特定的appsettings文件中的键和值。

public static void DoSomethingWithConfigurationManager(IConfiguration config)
{
    var root = config as ConfigurationRoot;
    if (root != null)
    {
        var appSettingsProvider = root.Providers.FirstOrDefault(x => x is JsonConfigurationProvider && ((JsonConfigurationProvider)x).Source?.Path == "appsettings.json") as JsonConfigurationProvider;
        if (appSettingsProvider != null)
        {
            var dataElement = appSettingsProvider.GetType().GetProperty("Data", BindingFlags.Instance | BindingFlags.NonPublic);
            var dataValue = (SortedDictionary<string, string>)dataElement.GetValue(appSettingsProvider);
            foreach (var item in dataValue)
            {
                //Do something with item.Key and item.Value
            }
        }
    }

0
请注意,我的网络应用程序针对.NET 7版本。
IEnumerable<IConfigurationSection> section = config.GetSection("Section1").GetChildren();

foreach (IConfigurationSection item in section)
{
    Debug.WriteLine($"Key: {item.Key}; Value:{item.Value}");
}

-4
我在我的 program.cs 文件中使用了这样的代码,它可以正确地获取 appsettings.json 文件中的值,你也可以试试这样做。

Program.cs

IHost host = new HostBuilder()            
                 .ConfigureAppConfiguration((hostContext, configApp) =>
                 {
                     configApp.AddJsonFile($"appsettings.json", true);
                     configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
}

appsettings.json

{
  "https_port": 443,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

3
这并不是原帖所问的内容。 - Panagiotis Kanavos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接