I'm new to developing in .Net, so I thought I'd start off with a .Net Core course. So far so good; I'm trying to create an API that requires specific keys to exist in a JSON object. If at least one of the keys is missing, I would expect it to be invalid.
[HttpPost("new")]
public IActionResult CreateGPSPoint([FromBody] ModelExample dataObject)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
}
IsValid returns true, however, even if I omit some, or all, of the keys in the JSON payload that I send. On inspection, those keys that were missing are set to 0 on the subsequent model's properties; so here's what my model looks like.
public class ModelExample
{
[Required(AllowEmptyStrings = false)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public float Height{ get; set; }
[Required(AllowEmptyStrings = false)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public decimal Width{ get; set; }
[Required(AllowEmptyStrings = false)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public int Depth{ get; set; }
//Populated by the entity later, but feel free to critique nevertheless
public int Id { get; set; }
}
Note that, since this kind of question has been brought up a few times elsewhere here, I have tried various combinations of Required(AllowEmptyStrings = false) and DisplayFormat(ConvertEmptyStringToNull = false) - my assumption was that these would be checked when the JSON object was "converted(?)" to the Model; however, the result has always been the same.
Initially I had thought this could be an issue with Automapper (which I am using), but validations pass before any entity/model mappings occur.
Those specific fields that I missed out can never be null, either, since no value will be set to 0 (and null would still be a valid value anyway).
My thought was to just interpret the data as a JSON object (instead of a ModelExample) and check that those keys exist early on in my controller logic (something like with Rails' "dataObject&.dig[:key]" - but I don't know if this is either possible or appropriate, or if there is a .Net tactic I've missed out.
My question really is; is something being done incorrectly, or missing from the above?
Many thanks in advance if anyone can provide enlightenment on how the above works!