问题描述
有些时候我们需要在 .NET Core appsettings.json 文件中配置键值对映射,如内外网的映射 OuterHostMappings:
{
"ASSRequestInfo": {
"Host": "http://192.168.1.31:9680",
"APPID": "OTS",
"OuterHostMappings": {
"192.168.1.31:9680": "35.125.221.31:80",
"192.168.1.32:8080": "35.125.221.31:81"
}
}
}
注意此处 OuterHostMappings 下面的 key 为 Ip + 端口,中间用冒号分隔,当系统启动时用字典格式去解析绑定,OuterHostMappings 为字典格式:
public class ASSRequestInfo
{
public string Host { get; set; }
public string APPID { get; set; }
public Dictionary<string, string> OuterHostMappings { get; set; }
}
绑定代码:
configuration.GetSection("ASSRequestInfo").Bind(ConfigModel.ASSRequestInfo);
很不幸,解析是会碰到如下错误(测试用的版本是.Net Core 3.1):
错误截图
错误信息是这样:Cannot create instance of type 'System.String' because it is missing a public parameterless constructor.
解决方案
碰到这个问题一时手足无措,网上也没有搜索到相关内容,经过多次测试发现 配置中的 Key (如:"192.168.1.31:9680") 如果 有冒号(:)存在就会报错,无奈配置中的冒号只好改成中划线,在使用的时候再去做字符替换:
{
"ASSRequestInfo": {
"Host": "http://192.168.1.31:9680",
"APPID": "OTS",
"OuterHostMappings": {
"192.168.1.31-9680": "35.125.221.31:80",
"192.168.1.32-8080": "35.125.221.31:81"
}
}
}
有知道原因的大神欢迎评论!









网友评论