Click here to Skip to main content
15,885,065 members
Articles / Web Development / HTML

Model Validation in ASP.NET Web API

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
10 Mar 2014CPOL2 min read 18.1K   3   1
Model Validation in ASP.NET Web API

In my previous articles, I discussed about MVC (Model-View-Controller) architecture as well as its implementation in details. I am expecting that the reader of this article already understand about the role of Model in an ASP.NET MVC application. Model in MVC is basically a representation of our data structure. So, here in this article, we are going to understand and implement the data annotation technique for applying validation on a model class for an ASP.NET Web API application.

In our ASP.NET Web API article series, we have already created an application that is performing all CRUD (Create, Retrieve, Update, Delete) operations using Web API. Here, we will take the same domain model class, i.e., "Student.cs" and apply validation on it using data annotation method. In order to better understand with more validation rules, I modified it a bit. So, here is our Model class:

C#
public class Student
{
        [Range(1, 500)]
        public int StudentID { get; set; }
[Required] [MaxLength(10)] public string 
                FirstName { get; set; } public string LastName 
                { get; set; } }

We have applied some validation to our model class properties in the same manner as a database table's fields have associated validation rules. We have applied the attributes to model properties using System.ComponentModel.DataAnnotations namespace.

Our Model class, i.e., Student has the following validation rules.

  • StudentID value must be between 1 and 500.
  • FirstName is also required with maximum length of 10.
  • LastName has no associated rule.

We will check the validity of Model against the defined validation rules in controller class, i.e., StudentController.

C#
1 public class StudentsController 
                : ApiController
2 {
3 public HttpResponseMessage Post(Student Student)
4 {
5 if (ModelState.IsValid)
6 {
7 // Valid scenario code here...
8 return new HttpResponseMessage(HttpStatusCode.OK);
9 }
. else
. {
. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
. }
. }
. }

Now, when the client will send a POST request in JSON format, it's being converted to Student object instance and that instance will be validated against the rules defined in Model class. In the above code sample, line # 5, Student instance state is validated and accordingly response is generated. Let's suppose if we post the following JSON to our ASP.NET Web API service one by one:

C#
{ "StudentID":942, "FirstName":"Imran", "LastName":"Ghani" }
{ "StudentID":100, "FirstName":"ImraaanAbdul", "LastName":"Ghani" }
{ "StudentID":101, "FirstName":"Imran", "LastName":"Ghani" }

JSON representation 1 & 2 will return with the message "Bad Request....Request is Invalid...." because:

  1. StudentID value is not between the defined validation range (1 to 500).
  2. FirstName maximum defined length exceeded.

JSON representation 3 is valid and response with status code of 200 will be returned.

Data annotation technique for Model validation is really helpful because it validates data before involving in any further processing. But there are some limitations associated with this approach, i.e., Under-Posting and Over-Posting. Hopefully, I will try to discuss these concepts in more detail in a separate post.

Readers of this article might also be interested in:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 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 WCF Tutorials, Web Development, SharePoint for Dummies.

Comments and Discussions

 
QuestionPlease help under this condition Under-Posting and Over-Posting. Pin
Aakash Bashyal18-Sep-15 16:33
Aakash Bashyal18-Sep-15 16:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.