asp.net-core - 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,这里一切正常
解决方案
最后我找到了我的问题的解决方案。这是发生了什么,对于 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; }
}
推荐阅读
- cytoscape.js - Cytoscape中文本背景填充的不同填充?
- azure - Azure 网关 VPN IP 与实际公共 IP 不同
- mysql - 使用 chpasswd 准备语句
- javafx - JavaFX 部署:无法启动 JVM
- laravel - 作业内作业的批处理或链接
- firebase - firebase_crashlytics 与 Flutter 的集成无法正常工作 我们将监听您的应用程序以与我们的服务器进行通信
- yarnpkg - Yarn 将单个包安装到单个工作区
- php - 谷歌支付 UPI 集成在 codeigniter
- python-3.x - 使用python后如何访问数据框的第一行
- c# - EF Core,包括派生类型属性