Chris H. Chris H. - 1 year ago 70
JSON Question

Web API calling accessor on all properties during deserialization from JSON

I've got a really puzzling issue relating to mapping data to a Model in my Web API. It's a bit complex, so let me know if I haven't explained it well enough and I'll do my best to elaborate.

See Edit 2, the problem has changed

I have a MVC 5 application in which the user submits form data and that data is mapped to a model automatically based on matching the names of the fields in the JSON with the names of the model's members. For example, if the incoming JSON for user names is of the form:

{Id=0, Name=testName}

Then there will be a model called (example name only)
that has an
int id
and a
string name
among other properties that don't need to be mapped from JSON (there are a number of these models for a number of different forms).

I'm not sure how useful it will be but I noticed that the call at the bottom of the stack trace was

ModelMetadata metadata, ValidationContext validationContext, Object container,
IEnumerable`1 validators)

Could this
have something to do with my probleM?

None of us have any idea as to why this is happening, and only happening on my machine. Any ideas/suggestions? Things to try? Ways to narrow down the error?

Edit: Found another question which may be related, but it's really odd that this only occurs on my computer, whereas in that post it was just a general problem.

Edit 2: I've narrowed down the issue, and have a much more specific problem now. I have discovered that on my computer the Web API's mapping of the JSON to the C# object (or some other process called during the mapping) calls the
for each property in the process of mapping the object. This is why the exception is being thrown; one of the properties throws an exception when the
is called (by design). On others' computers, the
is called only on those properties that are mapped to by the JSON, and we're not sure why.

Edit 3 (revised): In researching
I found this post which asked how to disable it. I followed the instructions in the accepted answer and disabled the default validation, and my issue went away! I'm still left with the question as to why this would be different between two computers, but at least I'm getting somewhere!

Answer Source

I was able to solve my problem by disabling the default System.Web.HTTP.Validation validation on my entire project. See this stack post for where I got the solution, which is shown below:


If this is put at the top of the RouteConfig file, the default validation will be disabled, and the issue does not occur. This still does not explain why it was only validating that property on my computer, and that question remains unanswered, however for the purpose of this question this solves the problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download