.NET WebAPI中的POST对象(POST object in .NET WebAPI)

编程入门 行业动态 更新时间:2024-10-28 12:28:43
.NET WebAPI中的POST对象(POST object in .NET WebAPI)

我对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.

更多推荐

本文发布于:2023-07-15 11:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1112844.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   WebAPI   NET   object   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!