【问题标题】:validate id route parameter for positive integers starting at 1验证从 1 开始的正整数的 id 路由参数
【发布时间】: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 开始的必需正整数?

【问题讨论】:

标签: c# .net .net-core asp.net-core-webapi


【解决方案1】:

你能不能试试最小的路由约束?

[HttpPatch("{id:int:min(1)}/last-name")]

如果您想在其他地方更严格,Id 属性也可以是 uint

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2019-03-02
  • 1970-01-01
  • 2016-03-04
相关资源
最近更新 更多