0

In a typical MVC controller, we can bind the Json body with a Model as long as all the parameters match like so:

[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. I want to be able to return a custom message instead. How can I validate the Json if this was the scenario?

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.

Kei
  • 315
  • 1
  • 4
  • 18

1 Answers1

0

1) Handle the Error

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

You can catch the errors at different levels, and return different error responses.

2) Fix the Input

Also consider that when different parts of a system agree to communicate in a given format (JSON) shouldn't both sides comply? It is also an error for the client to send broken JSON to you isn't it? That can be virtually eliminated by cleaning up the front end interface.

GantTheWanderer
  • 1,255
  • 1
  • 11
  • 19