Limitations to Model Validation in Web API

By | March 18, 2014

In my previous post on this blog, I explained data annotation technique with example for validating model in ASP.NET Web API. But there are certain limitations to this technique i.e. Under-Posting and Over-Posting. Purpose of this post is to discuss and understand these limitations with the help of an example. In order to fully understand the idea, I’ll strongly recommend to go through previous ASP.NET Web API tutorial first.Now take the same domain model class “Student” with validation applied using Data Annotation technique as follows:

Now there is a possibility that while calling the Web API service from client, JSON data may be sent for “Student” domain model with lesser details like the following. It’s referred as “Under-Posting“.

Now, as it’s missing “LastName” field in JSON string. So it will be treated as empty string in converted “Student” instance in service, just as if we sent empty value explicitly as follows:

Now this will be a problem in edit scenrio, where the initial value for LastName is “Ghani” and it will be replaced with empty string (which is not the intended action).

The other limitation to model validation in ASP.NET Web API is “Over-Posting” opposite to “Under-Posting” scenario discussed above. Similarly, there is a possibility that client sends more than expected data while calling a Web API service. For example, consider the following JSON string sending DOB (Date of Birth) as an additional property as follows:

In such scenarios, the additional property will be simply ignored. But one can say that if the JSON formatter is ignoring the additional value then where is the problem? Yes, it’s there.
For example, our Model class has an additional boolean field named as “IsCR” i.e. student is a Class Representative.

And we intentionally wanted to keep it as read-only. We don’t want the client to change the value of this field and simply upgrade a student to “Class Representative”.

In order to handle such scenarios, the best solution is to design our Model class exactly the same way what we are expecting from client. This is the best strategy to deal with such limitations while using Data Annotation in Model Validation.

Category: ASP.NET Web API

About Web Development

Imran Abdul Ghani is working as Software Developer(Senior) with extensive knowledge in Web development technologies especially C#, ASP.NET, MVC, WCF, Web API, ADO.NET Entity Framework, jQuery etc. He has several years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET (MCSD.NET) since 2005. You can reach his blogging at www.webdevelopmenthelp.net, www.topwcftutorials.net, and www.sharepointfordummies.net.