2

Here is a scenario I faced last week:

I sent an array of JSON objects to a WebAPI method with a signature like the following:

void Post(IEnumerable<ItemViewModel> items)

An example of the JSON array might look like (I've removed most of the properties for brevity):

[{ size: 1 }, 
 { size: 1.5 }, 
 { size: 2 }, 
 { size: 3 }, 
 { size: 1.25 }]

The View Model was something like the following (most properties removed for brevity):

public class ItemViewModel
{
    public int Size { get; set; }
}

The problem was that ItemViewModel's Size property is of type "int" and some of the JSON object's size properties were of type "double".

WebAPI didn't see the objects as a match for the type ItemViewModel, but it failed silently and still deserialized the other objects in the collection, just ignoring the ones that didn't match exactly.

Is there any setting/configuration point or other way to have WebAPI throw an exception or log a warning when this happens?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Gage Trader
  • 363
  • 2
  • 13
  • 1
    Have you tried to validate against a JSON schema? http://stackoverflow.com/questions/19544183/validate-json-against-json-schema-c-sharp – lcryder Mar 05 '15 at 18:06

1 Answers1

1

There are a couple of ways to do it.

First, the simplest, is to decorate your model with [Required] attributes and then call ModelState.IsValid. That'll tell you if something didn't deserialize right.

If you don't like going crazy decorating all your classes with attributes (I hate it), I hear good things about Fluent Validation.

You could also validate against a JSON schema.

Pharylon
  • 9,796
  • 3
  • 35
  • 59