appsettings config在我验证之前就被忽略了
我想要验证的 appSettings 中的配置如下所示:
"ListOfWork": [
{
"Name": "Work-1",
"StartDate": "2020-01-01",
"EndDate": "2021-01-01"
},
{
"Name": "Work-2",
"StartDate": "2021-01-01",
"EndDate": "invaliddate"
},
{
"Name": "Work-3",
"StartDate": "2022-01-01",
"EndDate": "20231-01-01"
}
]
Work 类如下所示:
public class Work
{
public string Name { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
}
这就是我在 Startup.cs
中获取配置的方式:
services.Configure<List<Work>>(Configuration.GetSection("ListOfWork"));
在给定的配置示例中,我想验证 appSettings 中提供的值是否良好,并且我们在自动验证 UTest 中进行验证,但即使在此之前,具有无效属性的对象已经被拒绝,并且唯一的我得到的
Work
对象是 Work-1
和 Work-3
。
有什么方法可以引发错误,而不是仅仅忽略无效对象?
The config in appSettings that I want to validate looks like this:
"ListOfWork": [
{
"Name": "Work-1",
"StartDate": "2020-01-01",
"EndDate": "2021-01-01"
},
{
"Name": "Work-2",
"StartDate": "2021-01-01",
"EndDate": "invaliddate"
},
{
"Name": "Work-3",
"StartDate": "2022-01-01",
"EndDate": "20231-01-01"
}
]
The Work
Class looks like this:
public class Work
{
public string Name { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
}
And this is how I'm fetching the config in Startup.cs
:
services.Configure<List<Work>>(Configuration.GetSection("ListOfWork"));
For the given example of the config, I would like to validate that the values provided in the appSettings is good and we do the validations in our automated validations UTests but even before that, the object with invalid attribute is already rejected and the only Work
objects I get are Work-1
and Work-3
.
Is there any way I could raise an error instead of just having the invalid object ignored?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,如果存在解析错误,则不会自动拾取AppSetting的属性。在您的情况下,“无效”这是一个字符串,转换为日期时间?不可能。我建议稍微调整工作类以定义字符串属性,而不是DateTime属性,您只能为DateTime Props掌握:
通过这种方式,解析将成功,您可以在DateTime Getters中检查DateTime的有效性。
请注意,我正在使用C#10功能,如果您使用旧版本,您可能无法完全运行此代码段,但是我可以明白,您可以提出自己的实现。
By default the properties from appsettings are not picked up automatically if there are parsing errors. In your case "invaliddate" it's a string and the conversion to DateTime? it's not possible. I'd suggest to slightly adjust the Work class to define string properties instead of DateTime properties and you can have only getters for the DateTime props:
In this way the parsing will be successful and you could check the validity of the datetime in the DateTime getters.
Note that I am using C# 10 features, you may not be able to fully run this code snippet if you re using an older version, but I thing you get the point and you can come up with your own implementation.