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]


Source: Indeed
Details: MVC:. ASP.NET MVC, ASP.NET AJAX,C#, C++, SSIS, Object Oriented Programming, T-SQL, JAVA, Telerik Controls, Javascript....  More
6 days ago

Guaynabo, PR 17-August-2017

Source: Indeed
Details: Experience in developing web applications using ASP.NET, MVC, Javascript, JQuery. CorTrust Bank is looking for a talented programmer to create secure and...  More
12 days ago

Mitchell, SD 11-August-2017

Application Developer -- C#, ASP.NET Web Forms/MVC
Source: Indeed
Details: .NET framework (3.5 or newer) -- especially with .NET Web Services, ASP.NET MVC, ASP.NET Web Forms and LINQ. We have a fulltime programmer position open for an...  More
1 day ago

Golden Valley, MN 22-August-2017

Sr. Developer / Architect - .Net MVC Angular 4.0
Source: Indeed
Details: Net. Developer / Architect - .Net MVC Angular 4.0*. Strong knowledge and working experience of ASP.NET MVC, Angular 4.0....  More
6 days ago

Miami, FL 17-August-2017

Sr Developer / Architect - .Net MVC Angular 4.0
Source: Indeed
Details: Strong knowledge and working experience of ASP.NET MVC, Angular 4.0 2. Essential experience - ASP.Net - Angular 4.0 - MVC 4 - C# - JavaScript, JSON, JQuery,...  More
6 days ago

Atlanta, GA 17-August-2017

Sr. .Net Developer
Source: Indeed
Details: ASP.NET web forms, ASP.NET MVC, EF. ASP.NET 4.5+, Visual Studio .NET 2012+, C#, MVC 4+, Web API (REST), HTML, jQuery, JavaScript, Knockout, Angular.JS,...  More
14 days ago

Homestead, PA 09-August-2017

.NET Developer
Source: Indeed
Details: 2+ Years of web development experience with ASP.NET and MVC 5. Hands on development of proprietary and third party applications using C#, ASP.NET, MVC , SQL....  More
30+ days ago

Chicago, IL 19-May-2017

Front End Developer
Source: Indeed
Details: Full stack experience with a backend such as Node, ASP.NET MVC, or Rails. Art of Context is a boutique, interactive firm that specializes in multi-channel...  More
2 days ago

Boston, MA 21-August-2017

Lead .NET Developer
Source: OutMatch
Details: MVC and MVVM front-end design and development with frameworks such as Kendo UI, knockout.js, Angular JS or similar. Lead .NET Developer....  More
18 hours ago

Dallas, TX 75251 23-August-2017

ASP.NET MVC, C# Developer
Source: Indeed
Details: MVC:. Has an immediate opening for an MVC, C# developer. Tech stack includes:....  More
24 days ago

Springfield, IL 30-July-2017

.NET Developer- Data Structure
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
6 days ago

Redmond, WA 17-August-2017

Source: Indeed
Details: ASP.NET MVC, JavaScript, HTML5, CSS3, and Bootstrap. Purpose of Position*....  More
30+ days ago

Plano, TX 75024 27-June-2017

Jr .Net Developer
Source: Indeed
Details: MVC Framework 6.0, AJAX, Angular 2, Bootstrap, CSS, 3rd party controls(Mandatory). Good communication and coordination skills working in onshore and...  More
9 days ago

Seattle, WA 14-August-2017

Front End Developer with Visual Studio experience (required)
Source: Indeed
Details: We are looking for an experienced Microsoft ASP.NET MVC developer with a focus on Front End technologies that can bring their expertise, experiences and...  More
16 days ago

Dallas-Fort Worth, TX 07-August-2017

ASP.NET MVC Developer, Lead
Source: Indeed
Details: MVC:. .NET MVC Developer, eWorld Project at DOJ*. We are looking for a lead developer for the .Net MVC team on a funded project at the Department of Justice...  More
13 days ago

Falls Church, VA 10-August-2017

Systems Engineer/.Net Developer (Secret Cleared)
Source: Indeed
Details: Basic understanding of Development Languages (C#, ASP.NET, MVC, SQL Server, Java, and JavaScript, and Oracle Products....  More
30+ days ago

Randolph AFB, TX 18-July-2017

C#/Full Stack Developer
Source: Indeed
Details: Two years demonstrated experience ASP.NET MVC 5+. C#/Full Stack Developer*....  More
5 days ago

Beaverton, OR 97005 18-August-2017

Web Developer - .NET
Source: Meridian Technology Group
Details: Required technical skills include C#, ASP.NET MVC, HTML, XML, Java Script, Visual Studio, PL/SQL, GIT, SOAP Web Services, Unit Testing with NUnit or MSTest,...  More
30+ days ago

Tualatin, OR 06-July-2017

.Net Developer Jr.
Source: Pinnacle Partners
Details: Bachelor’s Degreeis a hard requirement1-3years of web development experience.ASP.NET MVC (4.0 or higher)Knowledge and experience with JavaScript, LINQ and...  More
30+ days ago

St. Louis, MO 14-July-2017

.Net Developer, Sr
Source: Pinnacle Partners
Details: Job ID: DC19496976Pinnacle Partners is assisting our client in their search for a .NETDeveloperin their expanding office in the St. Louis area. This resource  More
30+ days ago

St. Louis, MO 14-July-2017

ASP.NET MVC Developer
Source: Indeed
Details: Experience in web development with ASP.NET MVC including C#, JQuery, JavaScript, AJAX, and Entity Framework....  More
5 hours ago

Houston, TX 23-August-2017

ASP.NET MVC Developer
Source: Indeed
Details: Strong understanding of ASP.NET, C#, LINQ, MVC, IIS, SQL Server. Contribute to the architecture and development of enterprise level CMS implementations....  More
11 hours ago

Beaverton, OR 97007 23-August-2017

.Net Developer
Source: WinterWyman
Details: Experience with Microsoft ASP.NET, MVC, Web API, and C#. Are you a skilled and dynamic .Net Developer looking to join an exciting company that specializes in...  More
12 hours ago

Danvers, MA 01923 23-August-2017

.Net Web Developer
Source: Indeed
Details: Agile Development /Test Driven Development, jQuery, ASP.NET MVC, SQL Server, SharePoint, Enterprise Search technologies....  More
13 hours ago

Washington, DC 23-August-2017

.Net Developer
Source: Indeed
Details: Strong experience with C#, ASP.NET MVC 4.0/5.0, JSON, SSIS, SSRS,. Experience in design, development and maintenance of Rich User Interactive SPA using...  More
1 day ago

New York, NY 22-August-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