我正在创建一个 .NET Core Web API 并想调用一个提交客户订单的端点。客户 ID 作为路由参数出现。在请求正文中,可以发送一组对象。每个对象都包含产品 ID 及其数量。但是这个字段是可选的,空订单也是可能的(产品可以稍后添加)。
所以我从这个 DTO 开始
public class CreateCustomerOrderByIdDto
{
[FromRoute]
public uint Id { get; set; }
[FromBody]
public OrderPosition[] OrderPositions { get; set; }
}
public class OrderPosition
{
[Range(1, uint.MaxValue)]
public uint ProductId { get; set; }
[Range(1, uint.MaxValue)]
public uint Amount { get; set; }
}
此请求 DTO 应使
OrderPositions
字段可选,但在添加项目时,该项目需要两个属性。我想为 OrderPositions
设置一个默认值如果丢失所以我认为这个数据注释可以做到[DefaultValue(new OrderPosition[0])]
不幸的是我收到此错误消息
An attribute argument must be a constant expression, 'typeof()' expression or array creation expression of an attribute parameter type
那么如何将该字段标记为可选并设置默认值呢?
当不传递任何订单位置时,数组将转换为空数组,这样我就可以避免空检查并使用从未运行的循环
最佳答案
也许你可以使用 List<OrderPosition>
而不是数组。然后在构造函数中将其初始化为空列表
public class CreateCustomerOrderByIdDto
{
public CreateCustomerOrderByIdDto()
{
this.OrderPositions = new List<OrderPosition>();
}
[FromRoute]
public uint Id { get; set; }
[FromBody]
public List<OrderPosition> OrderPositions { get; set; }
}
public class OrderPosition
{
[Range(1, uint.MaxValue)]
public uint ProductId { get; set; }
[Range(1, uint.MaxValue)]
public uint Amount { get; set; }
}
关于c# - 空数组的默认值数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62204066/