用于 IDictionary<string, object> 的 Asp.Net Core 自定义转换器 appsettings JSON [英] Asp.Net Core custom converter appsettings JSON for IDictionary<string, object>
问题描述
我想读取 appsettings 文件,但是当一个属性定义为 IDictionary 时出现问题:值被转换为字符串.
I would like to read appsettings file, but I have problem when one property is defined as IDictionary: the values are converted as string.
例如我在 appsettings 中定义了:
For example I have in appsettings defined:
"Queue":{
"Name": "Test1",
"Durable": true,
"Exclusive": false,
"AutoDelete": false,
"Arguments": {
"x-expires": 10000,
"x-overflow": "drop-head",
}
},
绑定类定义为
public class QueueSettings
{
public string Name { get; set; } = "";
public bool Durable { get; set; } = true;
public bool Exclusive { get; set; } = false;
public bool AutoDelete { get; set; } = false;
public IDictionary<string, object> Arguments{ get; set; }
}
并且绑定完成为
QueueSettings queueSettings = new QueueSettings();
settings.GetSection("Queue").Bind(queueSettings);
在这个例子中 queueSettings.Arguments["x-expires"] 是字符串 ("10000"),但我希望它是整数.如何在 Net Core 服务集合中设置 JsonConverter?我知道它不使用 NewtonJson 所以 JsonConverter 属性没有帮助.
In this example queueSettings.Arguments["x-expires"] is string ("10000"), but I'd like it as integer. How can I set JsonConverter in Net Core services collection? I understand that it does not use NewtonJson so JsonConverter attribute does not help.
推荐答案
您可以根据需要手动绑定.
You can manually bind if you want as you want.
services.Configure<QueueSettings>(configs =>
{
configs.Name = configuration.GetSection("Queue").GetValue<string>("Name");
configs.Arguments.Add("x-expires", configuration.GetSection("Queue:Arguments").GetValue<int>("x-expires"));
});
这篇关于用于 IDictionary<string, object> 的 Asp.Net Core 自定义转换器 appsettings JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!