以下程序:
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
namespace ConsoleApp3
{
class Program
{
static void Main()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var options = configuration.Get<Options>();
foreach (var kvp in options.Values)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
}
internal class Options
{
public Dictionary<string, bool> Values { get; } = new Dictionary<string, bool>();
}
}
在获得此appsettings.json
文件后,它可以完美运行:
{
"Values": {
"a": true,
"b": false
}
}
但是将appsettings.json
的内容更改为此:
{
"Values": {
"a:b": true,
"b": false
}
}
我得到这个异常:
未处理的异常:System.InvalidOperationException:无法创建类型为System.Boolean的实例,因为它缺少公共的无参数构造函数。
堆栈跟踪:
at Microsoft.Extensions.Configuration.ConfigurationBinder.CreateInstance(Type type)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindDictionary(Object dictionary, Type dictionaryType, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindProperty(PropertyInfo property, Object instance, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindNonScalar(IConfiguration configuration, Object instance, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Get[T](IConfiguration configuration, Action`1 configureOptions)
at ConsoleApp3.Program.Main() in D:\Dev\ConsoleApp3\ConsoleApp3\Program.cs:line 15
我在做什么错?请注意,键中包含冒号是完全合法的json,但是也许不支持在appsettings.json文件中存储任何奇数字典?
答案 0 :(得分:1)
引用Configuration in ASP.NET Core: Hierarchical configuration data
Configuration API能够通过使用配置键中的定界符将分层数据展平来维护分层配置数据。
将文件读入配置时,将创建唯一键,以维护配置源的原始分层数据结构。这些部分和键使用冒号(:)展平以保持原始结构
这意味着在以下 appsettings.json 文件
中{
"Values": {
"a:b": true,
"b": false
}
}
按键将被压平
当ConfigurationBinder.BindDictionary
试图绑定Dictionary<string, bool>
中的Options
属性时,它将破坏设置文件的结构
也引用了此GitHub Issue
冒号在键中保留有特殊含义,因此不应将其用作常规键值的一部分。