coppro
coppro

Reputation: 14526

Make WebAPI reject unknown fields when binding JSON to a model

In ASP .NET WebAPI, consider the following simple model class:

public class Model {
    public string Value { get; set; }
}

If I have a controller method that takes this as a parameter:

[HttpPut]
public HttpResponseMessage PutModel(Model data)
{
    if (!ModelState.IsValid)
        return Request.CreateResponse(HttpStatusCode.BadRequest);

    // more code ...
}

and I pass in { "unknown": "value" } as the request body, the model binder will gleefully succeed, completely ignoring the unknown field. This is not very acceptable for future-proofing, since we want to reserve all possible field values and error out if they are provided rather than just silently fail, allowing someone to shoot themselves in the foot later on.

How do I make the model binding error on unknown fields?

Upvotes: 4

Views: 1849

Answers (1)

Alex
Alex

Reputation: 158

Maybe this solution, from Brian Rogers, can help...

"The Json.Net serializer has a MissingMemberHandling setting which you can set to Error. (The default is Ignore.) This will cause the serializer to throw a JsonSerializationException during deserialization whenever it encounters a JSON property for which there is no corresponding property in the target class."

At: Can you detect if an object you deserialized was missing a field with the JsonConvert class in Json.NET

I not tested here but if you get data direct from the HttpRequest and try to deserialize by following Brian Rogers method you could use this Json.Net setting.

Upvotes: 3

Related Questions