.net6 - 我工作正常
{
"SomeSetting": {
"A": "value1",
"B": "value2"
}
}
internal class MyClass // <-- NOTE, the class is internal
{
public string A { get; set; } // <-- but property must be public, including public setter
public string B { get; set; }
}
. . . . .
var inst = config.GetSection("SomeSetting").Get<MyClass>();
效果很好^^。
但除非属性具有名称或访问级别 - 公共,否则它不具有约束力。有可能有这样的东西吗? --
internal class MyClass
{
internal string A { get; set; } // <-- internal
internal string B { get; set; }
}
or
internal class MyClass
{
public string A { get; internal set; } // <-- internal setter
public string B { get; internal set; }
}
or
internal class MyClass
{
[SomeAttribute()]
internal string A { get; set; } // <-- internal
// or
[SomeOtherAttribute("B")]
internal string BBB { get; set; } // <-- property name is not matching json file
}
我没有深入研究DLL,我认为这是JSON绑定,所以我尝试了using System.Text.Json.Serialization;
JsonPropertyNameAttribute
JsonIncludeAttribute
但到目前为止 - 没有运气
我找到了路。这System.Text.Json 的不变性 https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-immutability?pivots=dotnet-6-0@KirkWoll 提供的(谢谢 - 很好的学习)不起作用。我想,我不能保证.Get<MyClass>()
使用该技术。我尝试了文档中描述的所有方法,但没有成功。
但有一个简单的方法,就在那里。您只需像这样创建只读模型
public class MyClass
{
public string A { get; private set; }
public string B { get; private set; }
}
并像这样绑定它 - 使用附加选项
var inst = config.GetSection("SomeSetting")
.Get<MyClass>(options => { options.BindNonPublicProperties = true; });
这解决了只读模型绑定到 JSON 的问题IConfiguration
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)