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
}
CodePudding user response:
"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 useModelState.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 inspectModelState.IsValid
and react appropriately. So you should useModelState.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
Hope above steps guided you accordingly.