简体   繁体   中英

Data Annotation model validation for Required attribute

In my web api project, I have this code which uses Data Annotation Required attribute to validate. But when I test it using Postman, it can still go through.

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

在此处输入图像描述

"In my web api project, I have this code which uses Data Annotation Required attribute to validate. But when I test it using Postman, it can still go through.?"

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.

Controller

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

Note: Its should also work even you don't use ModelState.IsValid attribute because model validation executes before the controller being executed .

Output:

在此处输入图像描述

Hope the above steps guided you accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM