Limitations to Model Validation in ASP.NET Web API

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:

public class Student

{

    [Range(1, 500)]

    public int StudentID { get; set; }

    [Required]

    [MaxLength(10)]

    public string FirstName { get; set; }

    public string LastName { get; set; }

} 

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".

{"StudentID":101, "FirstName":"Imran"}

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:

{"StudentID":101, "FirstName":"Imran", "LastName": ""}

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:

{ "StudentID":101, "FirstName":"Imran", "DOB": "08-10-1990"}

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.

public bool IsCR { get; set; }

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.

To read more blog: webdevelopmenthelp