首页 > 解决方案 > asp.net core 2.2 - 必需属性不适用于十进制和整数

问题描述

我正在使用 net core 2.2 web api,我想为每个请求验证我的身体。验证对于数据类型 string 工作正常,但对于 int 和 decimal 它们不起作用。

我的模型类如下:

public class IcuTherapyO2Request
    {
        [Required(ErrorMessage = "Mr Number is required")]
        public int mrNo { get; set; }
        [Required(ErrorMessage = "Type is required")]
        public string type { get; set; }
    }

我的控制器

// create
        #region
        [HttpPost("create")]
        public async Task<IActionResult> create([FromBody] IcuTherapyO2Request icuTherapyO2Request)
        {
            try
            {
                var claimsIdentity = this.User.Identity as ClaimsIdentity;
                var userId = claimsIdentity.FindFirst("id")?.Value;
                icuTherapyO2Request.createdBy = userId;
                var response = await _icuIORepository.create(icuTherapyO2Request);
                return Ok(response);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new Error { });
            }
        }
        #endregion

案例 1:我忘记在帖子正文中传递字符串类型的对象

{
   mrNo: 2
}

现在我收到以下错误:{“errors”:{“type”:[“Type is required”]},“title”:“发生了一个或多个验证错误。”,“status”:400,“traceId”: “0HM66ODDT3V8O:00000002”}

案例 2:我忘记在帖子正文中传递 number 类型的对象

    {
       type: "string"
    }

即使缺少 mrNo,这里一切正常

标签: asp.net-core

解决方案


最后我找到了我的问题的解决方案。这是发生了什么,对于 int 和 decimal 类型,即使未传递对象,asp.net 核心模型也会将 0 分配为默认值,因此我添加了更多验证以使用RANGE仅接受从 1 开始的值。

我的更新模型如下:

public class IcuTherapyO2Request
    {
        [Range(1, int.MaxValue, ErrorMessage = "Mr Number is required")] // this makes it to work
        [Required(ErrorMessage = "Mr Number is required")]
        public int mrNo { get; set; }
        [Required(ErrorMessage = "Type is required")]
        public string type { get; set; }
    }

推荐阅读