我对WebApi有一个小问题。
问题 :如果我想使用JSON发布模型,只要模型中定义的成员存在,我就可以添加任意数量的成员。
问题 :如果我的Json对象中存在未定义的成员,如何触发异常。 如果没有自定义的JsonConverter,这是否可以实现? 我正在寻找的是一个通用的解决方案,而不是每个不同型号的转换。
示例 :
模型:
public class Person { [Required] public string Name { get; set; } }Api控制器:
public class PersonController : ApiController { public HttpResponseMessage Post(Person person) { if (person != null) { if (ModelState.IsValid) { //do some stuff return new HttpResponseMessage(HttpStatusCode.OK); } } return new HttpResponseMessage(HttpStatusCode.BadRequest); } }Json帖子(正文) {"Name":"Joe"} - >有效{"Name":"Joe","InvalidMember","test","Name","John"} - >也有效。 在这种情况下,我想触发一个异常。 因为如果你看它,它与我的modeldefinition完全不符。
I have a small problem with the WebApi.
Problem: If I want to post a model using JSON, I can add as many members I want, as long as the members defined in model are present.
Question: How can I trigger an exception, if an undefined member is present in my Json object. Is this achievable without a custom JsonConverter? What I'm looking for is a generic solution, not a convertion for every different model.
Example:
Model:
public class Person { [Required] public string Name { get; set; } }Api Controller:
public class PersonController : ApiController { public HttpResponseMessage Post(Person person) { if (person != null) { if (ModelState.IsValid) { //do some stuff return new HttpResponseMessage(HttpStatusCode.OK); } } return new HttpResponseMessage(HttpStatusCode.BadRequest); } }Json posts (body) {"Name":"Joe"} --> valid {"Name":"Joe","InvalidMember","test","Name","John"} --> also valid. In this case I want to trigger an Exception. Because if you look at it, it doesn't match my modeldefinition exactly.
最满意答案
你可以尝试的一件事是玩这个设置:
config.Formatters.JsonFormatter.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;当存在JSON中无法识别的额外属性时,它应该为您提供无效的模型状态。
One thing you could try is playing around with this setting:
config.Formatters.JsonFormatter.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;It should give you an invalid model state when there are extra properties that aren't recognized in the JSON.
更多推荐
发布评论