【发布时间】:2020-09-24 08:56:24
【问题描述】:
所以给定这个示例端点来更新客户的姓氏
[HttpPatch("{id:int}/last-name")]
public async Task<ActionResult<object>> UpdateCustomerLastNameByIdAsync(UpdateCustomerLastNameByIdDto updateCustomerLastNameByIdDto)
{
// ...
}
我创建了这个 DTO 来验证 id 和姓氏。
public class UpdateCustomerLastNameByIdDto
{
[FromRoute]
public int Id { get; set; }
[FromBody]
[StringLength(50, MinimumLength = 1)]
[Required]
public string LastName { get; set; }
}
所以LastName 的验证工作正常。但是当使用这个 url https://localhost:5001/customers/-5/last-name 调用端点时,我希望 ID 为 -5。
出现两个问题:
- 调试时Id字段不是-5,是0。可能是url参数转换在下面的时候把它强制转换为0?
- 我的 ID 从 1 开始,所以 1 应该是最小值
我将属性 [Range(1, int.MaxValue)] 添加到 DTO 的 Id 字段中。再次调用 url 时,它工作正常。当调用 url https://localhost:5001/customers/123/last-name 时,我得到一个 400 和以下输出
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3d8afda-4ef45dce3935e1e0.",
"errors": {
"Id": [
"The field Id must be between 1 and 2147483647."
]
}
}
123 应该是一个有效的 id。那么如何验证 id 参数是否为从 1 开始的必需正整数?
【问题讨论】:
-
你可以试试这个网址localhost:5001/customers/123 吗?
标签: c# .net .net-core asp.net-core-webapi