c# - 为什么 c# 只验证我的一些必填字段
问题描述
我有这些模型:
public class Appointment
{
[Required]
public DateTime Start { get; set; }
[Required]
public string UserId { get; set; }
[Required]
public int Duration { get; set; }
[Required]
public Guid VisitingTypeId { get; set; }
[Required]
public int Status { get; set; }
[Required]
public Patient Patient { get; set; }
}
public class Patient
{
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
[Required]
public string Mail { get; set; }
[Required]
public string UserId { get; set; }
}
这是我的控制器:
[ApiController]
[Route("api/[controller]")]
public class SchedulerController : Controller
{
[AllowAnonymous]
[HttpPost("book-appointment")]
public async Task<IActionResult> BookAppointmentAsync([FromBody] Appointment appointment)
{
//some logic
}
}
为什么这个调用有效:
{
"UserId": "c6c988dc-04d7-40dd-a36b-dacd70adf617",
"Patient": {
"Mail": "as.asd@das.ch",
"UserId": "c6c988dc-04d7-40dd-a36b-dacd70adf617",
"Lastname": "asd",
"Firstname": "asd"
}
}
如果我删除用户 ID,我会收到需要用户 ID 的消息,例如,为什么 Duration 不是这种情况?
解决方案
正在验证所有必填字段。所有值类型都已满足所提供的要求,因为它们都具有非空默认值,并且您提供了UserId
当模型绑定器初始化类时,这些值类型都将具有非空值并满足[Required]
验证属性。
如果您要使它们为可空类型,
[Required]
public DateTime? Start { get; set; }
[Required]
public string UserId { get; set; }
[Required]
public int? Duration { get; set; }
[Required]
public Guid? VisitingTypeId { get; set; }
[Required]
public int? Status { get; set; }
[Required]
public Patient Patient { get; set; }
那么您将获得示例中显示的 JSON 的预期行为
ASP.NET Core 中的参考模型验证:服务器上的 [必需] 验证
推荐阅读
- angular - 在 ngOnInit 之后调用 ngOnDestroy
- android - 如何在键盘布局中使用 ViewStub
- themes - PrestaShop 1.6 - 无法覆盖主题中的模块 tpl 文件
- wordpress - WordPress,我们如何获取浏览器网络监控中显示的所有js和css文件
- mattermost - 为用户添加短文本/徽章/图标
- aws-sam - 原因:无效的模板属性或属性 [Api]
- c# - 授权属性在我的项目中不起作用
- azure - 当不同容器注册表上的新映像可用时,如何触发 azure devops 构建管道?
- azure - 由于缺少“授权”标头,身份验证失败
- postgresql - Postgresql 从 JSONB 字段中的对象数组中获取键