Model Validation in ASP.NET Web API

By | March 10, 2014

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; }

        [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 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
  • C. DELETE
  • 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]

Top ASP.NET MVC Jobs

Application Developer Journeyman Job
Source: CACI International
Details: ASP.NET MVC, Entity Framework (or other ORM), JavaScript, XML, JSON, Web API, and Powershell. Job Requisition Number:....  More
19 days ago

Reston, VA 07-July-2016

Application Developer Journeyman Job
Source: CACI International
Details: ASP.NET MVC, Entity Framework (or other ORM), JavaScript, XML, JSON, Web API, and Powershell. Job Requisition Number:....  More
19 days ago

Colorado Springs, CO 07-July-2016

C# / .NET Application Developer - Frankfort, KY
Source: NTT Data
Details: Demonstrated understanding of C#, ASP.NET, MVC and Microsoft SQL Server. Strong experience with MVC Framework, Visual Studio, and Microsoft SQL Server....  More
12 hours ago

Frankfort, KY 25-July-2016

.NET Application Developer
Source: CareWorks Tech
Details: 3+ years of experience with ASP. 3+ years of experience with ASP.net MVC w/ razor. .NET Application Developer....  More
5 days ago

California 20-July-2016

ASP.NET Application Developer
Source: DataBank
Details: WPF MVVM (or equivalent experience with ASP.Net MVC or WinForms). **THIS ROLE IS ON-SITE AT HUNTINGDON VALLEY, PA....  More
7 days ago

Horsham, PA 19-July-2016

.Net Application Developer / Software Programmer
Source: Wedbush Securities
Details: .Net, C#, ASP.Net, VB.NET, MVC, WCF, SQL Server 2008, Web Services, Windows Services, SDLC, XML, Ajax, SOAP, JSON, JQuery, Messaging Queue and Website...  More
7 days ago

Los Angeles, CA 90017 19-July-2016

Web Application / Ember.js Developer
Source: BitTitan
Details: Experience with at least one backend MVC framework such as .NET MVC, Rails, Django, Symfony2, Laravel, etc. Experience with ASP.NET MVC and Web Forms....  More
30+ days ago

Kirkland, WA 25-June-2016

Web Application Developer
Source: Booz Allen Hamilton
Details: Experience with MVC frameworks, including Apache Struts or Microsoft ASP.NET MVC and pattern-based software architecture and design preferred....  More
5 days ago

Annapolis Junction, MD 20-July-2016

.NET Application Developer
Source: FEi Systems, Inc.
Details: Knowledge of ASP.NET MVC. We are seeking a mid level .NET Developer to join our team....  More
10 days ago

Columbia, MD 15-July-2016

.Net Application Developer
Source: RSM US LLP
Details: Ability to apply system design and development methodologies Good oral and written communication skills Demonstrated work ethic and ability to work effectively...  More
30 days ago

Des Moines, IA 25-June-2016

.NET Application Developer II
Source: Indeed
Details: 4+ plus years of web-based software development in .NET (C#, ASP.NET, MVC, SQL Server). NET Application Developer II is responsible for delivering custom...  More
14 days ago

Chicago, IL 11-July-2016

Software Application WEB Developer
Source: Astral Images
Details: Know how to install and use JavaScript, Ajax, PHP, ASP, Java, Perl, and or C++. Familiarity with a multitude of web tools including HTML5, CSS3, Javascript,...  More
9 days ago

Austin, TX 16-July-2016

Web Application Developer (.NET/SharePoint)
Source: Victaulic
Details: C#, ASP.Net, MVC, JSON, XML, AJAX, Web Services, SQL. Web Application Developer (.Net/Sharepoint)....  More
9 days ago

Easton, PA 16-July-2016

Web Application Developer
Source: Indiana University Health
Details: Prefers experience with ASP.NET MVC, ASP.NET Web API, Microsoft Entity Framework, jQuery, JSON, WCF, HTML5, CSS3, AJAX, AngularJS, TypeScript and TFS....  More
12 days ago

Indianapolis, IN 13-July-2016

Web Application Developer
Source: Bloomington Hospital
Details: Prefers experience with ASP.NET MVC, ASP.NET Web API, Microsoft Entity Framework, jQuery, JSON, WCF, HTML5, CSS3, AJAX, AngularJS, TypeScript and TFS....  More
12 days ago

Indianapolis, IN 13-July-2016

Junior Developer
Source: Addx
Details: Provide development and software support for several systems utilizing .NET, ASP.NET MVC 5, SharePoint, C#, Visual Basic, PHP, SQL, JQuery, JavaScript, Ajax,...  More
5 days ago

Egg Harbor Township, NJ 20-July-2016

Web Application Developer
Source: MidwayUSA
Details: Are you interested in the outdoors? Have a passion for the Hunting and Shooting industry? Are you a Web Developer who likes working in an Agile Development...  More
15 days ago

Missouri 10-July-2016

.NET Senior Engineer - Kansas City
Source: The Nerdery
Details: We have opportunities to solve customer projects with a wide variety of frameworks and platforms such as ASP.NET MVC, Web Api, Umbraco, Sitecore, Entity...  More
19 days ago

Kansas City, MO 64106 07-July-2016

.NET Senior Engineer - Minneapolis
Source: The Nerdery
Details: We have opportunities to solve customer projects with a wide variety of frameworks and platforms such as ASP.NET MVC, Web Api, Umbraco, Sitecore, Entity...  More
19 days ago

Minneapolis, MN 07-July-2016

SR ASP.NET MVC Developer
Source: Copart, Inc
Details: Extensive familiarity with the .NET framework, ASP.NET MVC, ASP.NET Web API, C#, AngularJS, and TypeScript....  More
10 days ago

Dallas, TX 75254 16-July-2016

Web Application Developer
Source: Indeed
Details: Asp.NET, MVC with web forms, C#, Web API with WCF experience, html, JavaScript, CSS, AngularJS, RavenDB or other NoSQL databases, SQL stored procedures, SQL...  More
18 days ago

Cincinnati, OH 45203 07-July-2016

.NET Web Application Developer
Source: Indeed
Details: Extensive familiarity with the .NET framework, ASP, .NET, ASP.NET MVC, C# and JavaScript. .NET Web Application Developer*....  More
19 days ago

Louisville, KY 40223 06-July-2016

Only GC & USC Need Sr .NET Developer @ Chicago IL
Source: Indeed
Details: Deep understanding of DOM, AJAX, HTTP, ASP.NET MVC. Qualified candidates will have JavaScript, DOM, AJAX, HTTP, ASP.NET MVC and HTML. Hi,....  More
14 hours ago

Chicago, IL 25-July-2016

Web Administrator & Application Developer
Source: Ohio Dominican University
Details: A working knowledge of ASP.NET WebForms, ASP.NET MVC, Classic ASP, jQuery, and other current web-based technology being used by the university....  More
19 days ago

Columbus, OH 06-July-2016

Junior .NET Application Developer
Source: FEi Systems, Inc.
Details: Knowledge of ASP.NET MVC. We are seeking a junior level .NET Developer to join our team....  More
10 days ago

Columbia, MD 15-July-2016
Category: ASP.NET Web API Tags:

About IMRAN ABDUL GHANI

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.