【发布时间】:2020-03-03 15:51:04
【问题描述】:
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.";
}
}
}
结果:
Input |Output
-------------------|------
{ "bad" : "test" } | What?!
{ "Bar" : "test" } | What?!
{ "foo" : "test" } | Input is valid.
显然支持 JsonPropertyAttribute,因为我可以设置 PropertyName 并使其生效。但是,我希望 ModelState.IsValid 对于前两个示例输入为 false,因为 Required JsonProprty 参数设置为 Always。
如果我只是通过 JsonConvert 运行它:
JsonConvert.DeserializeObject<MyModel>(@"{'bad':'test'}");
反序列化过程中按预期抛出异常:
Result Message: Newtonsoft.Json.JsonSerializationException : Required property 'foo' not found in JSON. Path '', line 1, position 14.
【问题讨论】:
标签: c# asp.net asp.net-web-api json.net asp.net-web-api2