Model Validation in ASP.NET Web API

By | March 10, 2014
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest

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.Validation in ASP.NET Web API

In our ASP.NET Web API article series, we already have 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:

public class Student
        [Range(1, 500)]
        public int StudentID { get; set; }

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

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, its being converted to Student object instance and that instance will be validated against the rules defined in Model class. In above code sample, line # 5, Student instance state is validated and accordingly response is generated.

You are designing an ASP.NET Web API application. You need to select an HTTP verb to allow blog administrators to moderate a comment. Which HTTP verb should you use?

  • A. GET
  • B. POST
  • D. PUT

To further test your ASP.NET Web API skill, Take a Complete FREE Online Test or MCSD Practice Exam: 70-486 (Developing ASP.NET MVC Web Applications). Simply Click Here.

 Correct Answer: D

Let’s suppose if we post following JSON to our ASP.NET Web API service one by one:

  1. { “StudentID”:942, “FirstName”:”Imran”, “LastName”:”Ghani” }
  2. { “StudentID”:100, “FirstName”:”ImraaanAbdul”, “LastName”:”Ghani” }
  3. { “StudentID”:101, “FirstName”:”Imran”, “LastName”:”Ghani” }

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

  1. StudentID value 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. Follow the post for Limitations to Model Validation in ASP.NET Web API.

  • Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer] 28 Lectures, 2.5 Hours Video, Intermediate Level
    Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms.
  • AngularJS for ASP.NET MVC Developers [Brett Romero] 10 Lectures, 1 hour video, Intermediate Level
    The Fastest Way For .NET Developers To Add AngularJS To Their Resume
  • ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT] 77 Lectures, 10 hour video, All Level
    Latest approach of web application development
  • Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels
    From zero knowledge of ASP.NET to deploying a complete project to production.

More You Must Read about ASP.NET MVC & Related

Top 10 Interview Questions and Answers Series:

ASP.NET MVC Jobs in Dubai, United Arab Emirates [Updated Daily]


Seeking Lead .NET Developer
Source: Indeed
Details: The Lead Developer is responsible for building .NET applications using ASP.Net MVC, C#, Entity Framework, RESTFul, SOAP, SQL Server, JavaScript, and IIS....  More
11 days ago

Highlands Ranch, CO 10-October-2017

Lead .NET Web Developer
Source: Indeed
Details: C#, ASP.NET MVC, .NET Framework, SQL, Entity Framework/LINQ. Must have at least 7+ years professional working experience on ASP.NET MVC applications....  More
15 days ago

Irvine, CA 92606 07-October-2017

Lead, .NET Developer
Source: Gullview Technologies
Details: Proficient in C#, Visual Studio, MS-SQL, MVC, HTML, JavaScript. This position will be responsible for developing new features and functionality using the very...  More
15 days ago

Brainerd, MN 06-October-2017

Lead .Net Web Developer (LWD0102)
Source: Indeed
Details: C#, ASP.NET MVC, Web API, javascript, CSS, HTML, JSON, SQL Server, REST. We are seeking a Lead .Net Web Developer to join our energetic team in building our web...  More
16 days ago

Livonia, MI 05-October-2017

Sr. C#.NET Developer / Lead
Source: TechPeople
Details: Experience in Web application development with ASP.NET, MVC, HTML, JavaScript, CSS, and AJAX. Sr....  More
30+ days ago

Houston, TX 25-August-2017

Lead .NET Developer
Source: Nexient
Details: 8+ year’s experience in programming primarily around C# and ASP.NET, including ASP.NET MVC, Lambda expressions. Role and Responsibilities....  More
30+ days ago

Ann Arbor, MI 27-July-2017

: .Net Lead / Full Stack Developer
Source: Indeed
Details: O Bootstrap o AngularJS o ASP.NET MVC o ASP.NET Web API o Entity Framework • Experience developing user-facing software....  More
30+ days ago

Dayton, OH 07-July-2017

.NET Software Engineer
Source: Amano McGann, Inc
Details: Specific Responsibilities Develop software to meet business requirements & technical specifications Correct software bugs within specified dates, as required...  More
4 days ago

Roseville, MN 17-October-2017

Full Stack Developer - Must be local, WA
Source: Indeed
Details: Back End design and development, utilizing C#, .NET Framework, ASP.NET MVC, and ASP.NET WebAPI, to create new end-to-end web experiences and revise existing...  More
4 days ago

Redmond, WA 17-October-2017

Full Stack Web Developer
Source: Indeed
Details: Back End design and development, utilizing *C#, .NET Framework, ASP.NET MVC, and ASP.NET WebAPI,*. We are looking for a *full stack web developer*....  More
29 days ago

Redmond, WA 22-September-2017

Full Stack Developer
Source: Indeed
Details: *Requirements/Qualifications: * -Full stack developer with 3-5 years’ experience. -Previous experience building out enterprise level sites (1k+ users/hr) ...  More
30+ days ago

Redmond, WA 18-September-2017

Software Engineer
Source: Indeed
Details: ASP.NET MVC or Spring MVC (Java):. Asp.Net or Spring MVC:. We are looking for a passionate and skilled technologist/developer to join the EWE Global Product...  More
10 days ago

Bellevue, WA 11-October-2017

Web Developer Entry Level
Source: Johnson Controls
Details: C#, ASP.NET MVC, jQuery, EntityFramework preferred. What you will do....  More
3 days ago

Waynesboro, PA 18-October-2017

Full Stack Web Developer
Source: Seagull Scientific, Inc.
Details: Minimum of 2 years’ experience with C# ASP.NET MVC. This position would focus on HTML/CSS/JavaScript front-end and C# ASP.NET MVC back-end....  More
30+ days ago

Bellevue, WA 98007 25-August-2017

.Net Developer
Source: Indeed
Details: Knowledge of Classic ASP and VB6.0. Sigmaways is a leading IT consulting, staffing and business process outsourcing company based in Silicon Valley, California....  More
10 days ago

Bothell, WA 11-October-2017

.Net Front End Developer
Source: Indeed
Details: Strong experience in ASP.NET Web APIs and ASP.NET MVC. Job Title- SDE- Front End*....  More
1 day ago

Redmond, WA 20-October-2017

.Net Developer (Full Stack) - No C2C, must be local
Source: Indeed
Details: Middle tier (ASP.NET MVC / Java). Familiar with MVC, Entity Framework, ASP.NET. Very strong knowledge in data structures and proven record in using the best...  More
1 day ago

Redmond, WA 20-October-2017

.Net Developer
Source: Indeed
Details: Middle tier (ASP.NET MVC / Java). Familiar with MVC, Entity Framework, ASP.NET. Very strong knowledge in data structures and proven record in using the best...  More
30+ days ago

Redmond, WA 07-July-2017

Lead .Net & Mobile Developer
Source: Posh Technologies
Details: Visual Studio 2013+, C#, ASP.NET MVC 5 and Web API 2. 5+ years of working experience with C#, ASP.Net MVC, SQL Server, JavaScript....  More
30+ days ago

Redmond, WA 02-September-2017

Source: PSI Services LLC
Details: Minimum of 2+ years of experience developing ASP.NET MVC 4 + applications required. We are seeking a uniquely talented and creative .NET Software Engineer to...  More
12 days ago

Olathe, KS 09-October-2017

Software Engineer
Source: Genalyte Inc
Details: Strong expertise in one or more of the following web application frameworks - ASP.NET MVC, Ruby on Rails, Angular, Play!, YII Or Spring MVC....  More
16 days ago

San Diego, CA 92121 06-October-2017

Computer Engineer, Software Development
Source: Orolia
Details: Develop in ASP .NET MVC, develop new or modify existing API, UI/UX design and development, Database design and modeling....  More
25 days ago

Rancho Bernardo, CA 26-September-2017

Software Engineer
Source: SilverTech, Inc.
Details: Proficiency with Microsoft ASP.NET MVC, Web API. Manchester, NH Type :....  More
28 days ago

Manchester, NH 03104 23-September-2017

Full-Stack Software Engineer
Source: Chmura Economics and Analytics
Details: Experienced with a stack based on C#, ASP.NET MVC, Angular, SQL Server, and MongoDB. This Full-Stack Engineer position is a tremendous full time opportunity in...  More
29 days ago

Cleveland, OH 44115 22-September-2017

[Fall 2017] Software Development Intern, ASP.NET
Source: R&D Industries, Inc.
Details: Position Description: Thinix is seeking talented front-end and back-end web developers for Thinix Software Development Intern positions. Our Software...  More
30+ days ago

Ames, IA 50010 02-September-2017
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest
Category: ASP.NET Web API Tags:

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,, and