Joshua Dixon
Joshua Dixon

Reputation: 205

How to force Web API to throw an error when receiving an unmapped field in the request json

I'm building a REST API using Web API. The problem I am having is that the JSON serializer is not rejecting unmapped fields. Assuming I have a simple object like this:

public class MyClass
{
 public bool MyBool { get; set; }
 public string MyString { get; set; }
}

And I have a simple controller which accepts an object of this type in the body of a request

public void Post(MyClass instace)
{
   ...
}

Now, I post a request to the endpoint of this controller with the following JSON in the body of the request:

{ "MyBool":true, "MyString":"Valid", "InvalidField":"Invalid" }

Currently, the controller will quietly accept this request, mapping true to MyBool, and "Valid" to MyString while ignoring the InvalidField. How can I change this so that an error is thrown whenever an invalid field is present?

Upvotes: 4

Views: 1369

Answers (2)

I believe Required is not what you are looking for, since you are interested in extra fields that are present in the request. Required is for fields that are absent. You can read the JSON yourself and validate but to me that is a lot of work. So, piggy backing on binding is what something I would look at. I just wrote a small blog post to answer this question. Check it out http://lbadri.wordpress.com/2014/01/28/detecting-extra-fields-in-asp-net-web-api-request/.

Upvotes: 4

Dirk Huber
Dirk Huber

Reputation: 912

Apply the Required attribute to your member:

public class MyClass
{
 [Required]
 public bool MyBool { get; set; }

 [Required]
 public string MyString { get; set; }
}

See http://msdn.microsoft.com/library/system.componentmodel.dataannotations.requiredattribute.aspx

Upvotes: 0

Related Questions