首页 > 解决方案 > 遍历并读取 asp.net core 中的所有 appsettings 键

问题描述

我在我的 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不包含任何内容,如下面的屏幕截图所示: 在此处输入图像描述

我还需要做什么才能完成这项工作?

我试过var v = this._configuration.GetSection("Section1").GetSection("Key1");where _configurationis 的类型IConfiguration,它按预期工作。但同样,就像我提到的那样,我不想要这个,而是我想遍历 appsettings 中的所有键列表并对它们执行一些操作。

任何帮助都会很棒。

标签: asp.netasp.net-coreasp.net-web-apiasp.net-core-webapi

解决方案


像这样的东西可以让您专门迭代 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
            }
        }
    }

推荐阅读