I have created a controller method similar to
[HttpPost]
public ActionResult<MyDTO> Post([FromBody] MyDTO myDTO)
{
// do something with myDTO...
Ok();
}
and MyDTO:
namespace MyNamespace.DTO
{
public class MyDTO
{
[Required]
public int someNumber { get; set; }
[Required]
public bool someBool { get; set; }
[Required]
public DateTimeOffset someDate { get; set; }
}
}
When I send a post with a JSON body that doesn't have either defined, instead of returning a 400 or an exception of some sort, it just assigns default (falsy) values to them.
When I defined a List of another DTO class, it did return a 400 code.
How can I make the API return an error when certain required values are not provided instead of just using default values?
CodePudding user response:
You have to manually control it. There's no other way.
Try something like
[HttpPost]
public ActionResult<MyDTO> Post([FromBody] MyDTO myDTO)
{
if(YourComprobation(myDto)){
BadRequest();
}
Ok();
}
CodePudding user response:
Found an answer here.
I just had to make all the fields nullable and have a
if (!ModelState.IsValid)
// return 400
in the controller.