.net core Asp.Net核心自定义转换器appsettings JSON for IDictionary<;字符串,对象>;
我想读取appsettings文件,但当一个属性被定义为IDictionary时,我遇到了问题:这些值被转换为字符串 例如,我在appsettings中定义了:.net core Asp.Net核心自定义转换器appsettings JSON for IDictionary<;字符串,对象>;,.net-core,application-settings,jsonconverter,.net Core,Application Settings,Jsonconverter,我想读取appsettings文件,但当一个属性被定义为IDictionary时,我遇到了问题:这些值被转换为字符串 例如,我在appsettings中定义了: "Queue":{ "Name": "Test1", "Durable": true, "Exclusive": false, "AutoDelete": false, "Arguments": {
"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.Arguments[“x-expires”]是字符串(“10000”),但我希望它是整数。
如何在Net Core services集合中设置JsonConverter?
我知道它不使用NewtonJson,所以JsonConverter属性没有帮助。如果需要,可以手动绑定
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"));
});
services.Configure(配置=>
{
configs.Name=configuration.GetSection(“队列”).GetValue(“名称”);
configs.Arguments.Add(“x-expires”,configuration.GetSection(“Queue:Arguments”).GetValue(“x-expires”);
});
你确定吗?您能检查arguments数组的运行时类型吗?如果您强制转换为int,会引发异常吗?我猜你一定是在找什么地方,因为《论据》字典是肯定的!键“x-expires”字符串;值“10000”对象{string}@sommen我有ToString(),我对它进行了注释,但它没有帮助我只能认为,因为参数字典是Dict的,所以它会被更改为字符串而不是int。您可以始终使用Convert.Toint32(…)。不管怎样,你都需要施展它。你可以创建一个自动道具。为此:public int x-expires=>Convert.ToInt32(参数[“x-expires]”)代码>确定,但这仍然是一个解决方案。我可以用属性为int Expires的类替换参数。Im我的案例IDictionary应该让我能够直接将参数传递给第三方软件。即使在将来的新版本中它添加了一个新参数,我也不需要重写代码,在这种情况下是绑定类。问题是不可能添加自定义Json转换器。或者至少现有转换器应该区分“x-expires”:10000(整数)和“x-expires”:“10000”(字符串),
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"));
});