Required 属性的数据注释模型验证

Data Annotation model validation for Required attribute

在我的 Web api 项目中,我有这段代码使用 Data Annotation Required 属性进行验证。但是我用Postman测试的时候,还是可以通过的。

    public async Task<ActionResult> IsAccountClosed([Required] string nric)
    {
      // code removed for brevity
    }

“在我的 web api 项目中,我有这段代码使用 Data Annotation Required 属性来验证。但是当我使用 Postman 测试它时,它仍然可以通过。?”

The [Required] attribute allows you to use ModelState.IsValid construct. As model binding and model validation occur before the execution of a controller action or a Razor Pages handler method.it's the app's responsibility to inspect ModelState.IsValid and react appropriately. So you should use ModelState.IsValid inside then it would act what you are expecting.

控制器

public async Task<ActionResult> IsAccountClosed([Required] string nric)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            return Ok();
           
        }

注意: 即使您不使用 ModelState.IsValid 属性,它也应该有效,因为 model validationcontroller being executed 之前执行。

输出:

希望以上步骤能相应地指导您。