public class MyModel
{
[JsonProperty(PropertyName = "foo", Required = Required.Always)]
public String Bar;
}
public class MyController : ApiController
{
public String PostVersion1([FromBody] MyModel myModel)
{
if (ModelState.IsValid)
{
if (myModel.Bar == null)
return "What?!";
else
return "Input is valid.";
}
else
{
return "Input is invalid.";
}
}
}
Results:
Input |Output
-------------------|------
{ "bad" : "test" } | What?!
{ "Bar" : "test" } | What?!
{ "foo" : "test" } | Input is valid.
JsonPropertyAttribute is clearly supported because I am able to set the PropertyName and have it take effect. However, I would expect the ModelState.IsValid
to be false for the first two example inputs because the Required
JsonProprty parameter was set to Always.
If I just run it through JsonConvert:
JsonConvert.DeserializeObject<MyModel>(@"{'bad':'test'}");
an exception is thrown during deserialization as expected:
Result Message: Newtonsoft.Json.JsonSerializationException : Required property 'foo' not found in JSON. Path '', line 1, position 14.