简体   繁体   English

C#MVC验证发布到Controller Action的jsonString

[英]C# MVC Validate jsonString posted to Controller Action

In a typical MVC controller, we can bind the Json body with a Model as long as all the parameters match like so: 在典型的MVC控制器中,只要所有参数都匹配,我们就可以将Json主体与模型绑定:

[HttpPost]
public void PostPerson(Person p){
    //stuff
}

However, I noticed that using fiddler, if I were to do something like this: 但是,我注意到,如果要执行以下操作,请使用提琴手:

{
   "name":,
   "age": 12
}  

The controller will automatically return InternalServerError. 控制器将自动返回InternalServerError。 I want to be able to return a custom message instead. 我希望能够返回自定义消息。 How can I validate the Json if this was the scenario? 如果是这种情况,我如何验证Json?

I initially thought that an invalid Json will result in the Person object becoming NULL, so I made a handler for that to return a custom message, but after trying it here, that doesn't appear to be the case. 最初,我认为无效的Json会导致Person对象变为NULL,因此我为此创建了一个处理程序以返回自定义消息,但是在这里尝试了之后,情况似乎并非如此。

1) Handle the Error 1)处理错误

I would check out this article about error handling at different levels. 我将检查有关不同级别错误处理的本文。 http://www.dotnettricks.com/learn/mvc/exception-or-error-handling-and-logging-in-mvc4 http://www.dotnettricks.com/learn/mvc/exception-or-error-handling-and-logging-in-mvc4

You can catch the errors at different levels, and return different error responses. 您可以捕获不同级别的错误,并返回不同的错误响应。

2) Fix the Input 2)固定输入

Also consider that when different parts of a system agree to communicate in a given format (JSON) shouldn't both sides comply? 还应考虑到,当系统的不同部分同意以给定格式(JSON)进行通信时,双方都不应该遵守吗? It is also an error for the client to send broken JSON to you isn't it? 客户端向您发送损坏的JSON也是错误的,不是吗? That can be virtually eliminated by cleaning up the front end interface. 通过清理前端接口,几乎可以消除这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM