首页 > 解决方案 > 为什么 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 不是这种情况?

标签: c#asp.net-core

解决方案


正在验证所有必填字段。所有值类型都已满足所提供的要求,因为它们都具有非空默认值,并且您提供了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 中的参考模型验证:服务器上的 [必需] 验证


推荐阅读