c# - 列表未提供值时无法反序列化
问题描述
在类 Account 中,属性 Industry 是枚举类型 Industry 的集合
一个帐户可以属于多个行业的。
public class Account
{
[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public List<Industry> Industrys { get; set; }
}
Public enum Industry
{
AerospaceAirlines = 0,
Agriculture = 1,
Apparel = 2,
Automotive = 3,
Banking = 4,
BioTechnology = 5,
Chemicals = 6,
Communications = 7,
Construction = 8,
Consultancy = 9,
ConsumerDurables = 10,
Education = 11,
}
创建新账户时,不强制添加行业。当此 Industrys 属性的请求对象中未提供任何值时,将失败。
反序列化出现错误“值不能为空。\r\n参数名称:源”
当默认绑定器尝试填充 accountModel 对象时会发生故障。
[HttpPost]
public async Task<IActionResult> Post([FromBody]AccountModel accountModel)
{
if (accountModel == null)
{
throw new ApiException(ApplicationErrorCode.FieldRequiredError, "request cannot be empty");
}
}
如何允许发件人在没有提供行业的情况下发送请求?
解决方案
改变:
public class Account
{
[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public List<Industry> Industrys { get; set; }
}
到:
public class Account
{
[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public List<Industry> Industrys { get; set; } = new List<Industry>();
}
推荐阅读
- intellij-idea - Intellij:远程调试器未在断点处停止
- javascript - 订单更改时,Vue For-Loop 生成组件上的输入失去焦点
- python - 将其悬停在tkinter中时如何更改ttk按钮背景和前景
- powershell - 如何使用 PnP 更新修改者和创建者字段
- python-3.x - docplex 2.10.15x 的 TypeError
- java - GC 如何知道旧堆中的对象是否引用了年轻堆中的对象?
- visual-studio - 使用 Visual Studio 2019 进行 IIS Express 远程访问
- github - 无法通过 github 登录到screwdriver.cd
- react-native-android - 将 ExpoKit 从 SDk 32 更新到 SDK 33 后尝试创建发布 apk 时找不到名称为“compileClasspath”的错误配置
- python - 用2个空格Python替换不同数量的空格