C# 如何在appsettings.json中指定必填字段?
我有我的C# 如何在appsettings.json中指定必填字段?,c#,.net,asp.net-core,.net-core,configuration,C#,.net,Asp.net Core,.net Core,Configuration,我有我的appsettings.json,它工作得很好,只是它不允许我控制值是否存在 今天我遇到了一个bug,因为我忘了在config中放一个变量,它没有说。它只是使用了默认的字段值,在本地是正常的,但在另一台机器上崩溃了 我提出了以下解决方案: private static T Deserialize<T>(IConfigurationRoot configuration, string sectionName) where T : new() { var result =
appsettings.json
,它工作得很好,只是它不允许我控制值是否存在
今天我遇到了一个bug,因为我忘了在config中放一个变量,它没有说。它只是使用了默认的字段值,在本地是正常的,但在另一台机器上崩溃了
我提出了以下解决方案:
private static T Deserialize<T>(IConfigurationRoot configuration, string sectionName) where T : new()
{
var result = new T();
var configurationSection = configuration.GetSection(sectionName);
configurationSection.Bind(result);
foreach (var propertyInfo in typeof(T).GetProperties())
{
var value = propertyInfo.GetValue(result);
if (value == null || value is string s && s == "")
{
throw new ArgumentException($"All configuration fields are required but {propertyInfo.Name} is missing");
}
}
return result;
}
private static T反序列化(IConfigurationRoot配置,string sectionName),其中T:new()
{
var结果=新的T();
var configurationSection=configuration.GetSection(sectionName);
configurationSection.Bind(结果);
foreach(typeof(T).GetProperties()中的var propertyInfo)
{
var值=propertyInfo.GetValue(结果);
如果(值==null | |值为字符串s&&s==“”)
{
抛出新ArgumentException($“需要所有配置字段,但缺少{propertyInfo.Name}”);
}
}
返回结果;
}
但它显然不适用于值类型。它也不能处理故意为null或空字符串的值。我需要原始的JSON表示或一些API来验证字段的存在,但我还没有找到它
我试图从部分获取JSON,通过Newtonsoft.JSON
解析它,但同样没有成功
有什么建议吗?我建议看一看。将值类型设为null,这样就可以了。@KirkLarkin选项看起来可以,但还有一个包装器。为什么我首先需要
IOption
?我想它们只需要重新加载和其他东西。我通常希望我的模型不依赖于对可扩展性基础设施的任何了解。这很好。如果您不喜欢选项包装器之类的东西,那么选项验证就不适合您。我建议您看看。将值类型设为null,这样可以很好地工作。@KirkLarkin选项看起来可以工作,但还有另一个包装器。为什么我首先需要IOption
?我想它们只需要重新加载和其他东西。我通常希望我的模型不依赖于对可扩展性基础设施的任何了解。这很好。如果您不喜欢选项包装器之类的,那么选项验证不适合您。