I have following Controller Post method:
[Route("")]
[ResponseType(typeof(CardPost))]
[HttpPost]
public IHttpActionResult PostCard([FromBody] CardPost CardMetaData)
{
if (!ModelState.IsValid)
{
BadRequest(ModelState);
}//Property is not caught by ModelState
if (CardMetaData.Property == 0)
{
return BadRequest();
}
//Else insert to DBContext
}
I'm trying to bind and validate data using following Model class:
class CardPost
{
[Required(ErrorMessage = "property is required")]
[JsonProperty("property")]
public int Property { get; set; }
[Required(ErrorMessage = "Card Nr. is required")]
[StringLength(6,ErrorMessage ="Card Nr. is 6 characters")]
[JsonProperty("number")]
public string Number{ get; set; }
[Required(ErrorMessage ="Card Code is required")]
[JsonProperty("code")]
public string Code{ get; set; }
[Required(ErrorMessage = "blocked is required")]
[JsonProperty("blocked")]
public bool Blocked { get; set; }
}
Required attribute works fine for Number and Code but Property and Blocked nevers throw Exception even if not included in POST request. A workaround is to do manuel validation as above but I wonder what is behind this? The problem is showing only in one of my Controllers.