【发布时间】:2019-04-09 19:08:52
【问题描述】:
我们使用.NET Web API 和SQL Server。我从 API 获得的默认错误响应似乎因列的数据类型而异。在前端,我们有一个用户填写的表,它填充了上述数据库表。如果我为所有这些必填字段提交包含空白值的记录,这就是 API 在控制台中返回的内容(在“网络”-->“响应”选项卡中):
{
"Message": "The request is invalid.",
"ModelState": {
"myTable": [
"Required property 'columnInt1' not found in JSON. Path '', line x, position xxx.",
"Required property 'columnInt2' not found in JSON. Path '', line x, position xxx.",
"Required property 'columnInt3' not found in JSON. Path '', line x, position xxx.",
"Required property 'columnDecimal' not found in JSON. Path '', line x, position xxx."
],
"myTable.columnString1": [
"The columnString1 field is required."
],
],
"myTable.columnString2": [
"The columnString2 field is required."
]
}
}
请注意根据数据类型的不同错误响应。如果我将其中一个 varchar 列更改为 int 或 decimal 数据类型,其错误响应会更改以匹配其余 int/decimal 列具有 ("Required property 'columnInt1' not found in JSON. Path '', line x, position xxx") 的消息。
我希望所有错误都具有两个 varchar 列的响应("The stringColumn1 field is required." 等)。 有没有办法修改这个默认行为,为什么会这样?
下面是我们的表格设计示例:
Column Name: Data Type: Allow Nulls:
columnInt1 int no
columnInt2 int no
columnInt3 int no
columnDecimal decimal(5, 2) no
stringColumn1 varchar(4) no
stringColumn2 varchar(5) no
此表的 API 模型如下所示:
[Required]
public int columnInt1 { get; set; }
[Required]
public int columnInt2 { get; set; }
[Required]
public int columnInt3 { get; set; }
[Required]
[Precision(4,2)]
public decimal columnDecimal { get; set; }
[Required]
[StringLength(4)]
public string columnString1 { get; set; }
[Required]
[StringLength(5)]
public string columnString2 { get; set; }
【问题讨论】:
标签: sql-server database asp.net-web-api database-design model