asp.net - 遍历并读取 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 _configuration
is 的类型IConfiguration
,它按预期工作。但同样,就像我提到的那样,我不想要这个,而是我想遍历 appsettings 中的所有键列表并对它们执行一些操作。
任何帮助都会很棒。
解决方案
像这样的东西可以让您专门迭代 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
}
}
}
推荐阅读
- javascript - getstream.io NotificationDropdown 显示为空
- swift - 为什么我的应用在 ipad 上看起来是模拟的?
- c++ - 如何通过删除最少字符数来获取子字符串?
- python - tkinter 模块中的语法错误。root = tk() TypeError: 'module' object is not callable
- html - Chrome 中的 Padding-inline-start 错误的 CSS 动画
- java - 将类类型存储为变量以在 java 的列表中识别下一个预期的对象类型
- google-bigquery - 比较 2 个表并使用具有最大值 Bigquery 的行更新最终表
- layout - 聚焦时门户行可编辑字段表现奇怪(FileMaker Pro 18)
- java - xml中的*替换表示任何字符串是什么
- wordpress - {多个项目} Woocommerce