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

Web Developer - Remote/Work from home opportunity
Source: Food Services of America
Details: Strong understanding of ASP.NET MVC. 3+ years experience with ASP.NET Forms and ASP.NET MVC. For our web development efforts we create new applications using...  More
13 days ago

Remote 18-June-2016

Sr. .Net Backend Developer
Source: Indeed
Details: Minimum 4 years experience with writing WinApi/RESTFul API and working in an ASP.NET MVC environment.Strong understanding of OO principles and SOLID design...  More
5 days ago

Seattle, WA 25-June-2016

.Net Tech Lead (Job ID: 463259)
Source: Indeed
Details: Have the ability to develop with C#, ASP.NET, MVC (8 Years Required). Extensive Technical lead experience (8 Years Required)....  More
4 days ago

Des Moines, IA 26-June-2016

C# .Net Developer Full Stack asp.net / MVC
Source: Indeed
Details: ASP. Net, C#.Net, HTML, XML. Experience with responsive web design utilizing HTML, CSS, J-Query and Bootstrap....  More
8 days ago

Gainesville, GA 22-June-2016

Dot Net Architect lead
Source: Indeed
Details: Dot Net Architect:. Lead Dot Net Architect. Have the ability to develop with C#, ASP.NET, MVC. \*Apply only if you can attend an inperson interview and have...  More
8 days ago

Des Moines, IA 22-June-2016

.NET Lead
Source: Indeed
Details: C# .NET experience, ASP.NET MVC experience, Healthcare Industry experience, SQL server (3yrs):. _The .NET Lead is responsible for maintaining a strong customer...  More
10 days ago

Glennville, GA 20-June-2016

Entry Level Application Developer
Source: Omnitracs
Details: ASP.Net MVC 3.0+ framework. The Associate Software Engineer is responsible for playing a contributing role on a team focused on the development of software used...  More
9 days ago

Towson, MD 22-June-2016

Sr. Applications Developer
Source: Ruan
Details: Experience using the Microsoft stack with extensive knowledge in C#, SQL Server and ASP.NET MVC. Sr....  More
30+ days ago

Des Moines, IA 03-May-2016

.NET Developer
Source: Indeed
Details: ASP.Net MVC Framework. Graphic Products is seeking a .NET Web Developer to join our IT department....  More
15 days ago

Beaverton, OR 97008 15-June-2016

Sr. Dot Net Developer
Source: Indeed
Details: *Title: S* enior .Net Developer *Location: * Harrisburg, PA *Duration: * 6 Years Please share the profile having 9+years only. *Job Details : * * Asp.net *...  More
1 day ago

Harrisburg, PA 29-June-2016

Sr.Net Developer
Source: Indeed
Details: *Title: S* enior .Net Developer *Location: * Harrisburg, PA *Duration: * 6 Years Please share the profile having 9+years only. *Job Details : * * Asp.net *...  More
1 day ago

Harrisburg, PA 29-June-2016

Sr. ASP NET Developer (HIPAA)
Source: Cambria Solutions, Inc
Details: The Company Founded in 2003, Cambria Solutions, Inc. (Cambria) is a national information technology and management consulting firm headquartered in Sacramento  More
2 days ago

Sacramento, CA 29-June-2016

Sr .Net Developer
Source: Indeed
Details: *Job Title* : *Sr .Net Developer* *Duration: * *Full time* *Location: * Chicago,IL Responsibilities: - Performing as a Senior Developer on software...  More
2 days ago

Chicago, IL 28-June-2016

.Net Application Developer/.Net Developer
Source: Indeed
Details: 3+ Years of experience in ASP.Net, ASP.NET MVC, C#, Oracle and SQL Server Databases. This is a full time permanent position with a direct client, not a contract...  More
19 days ago

Brea, CA 11-June-2016

Sr. C#/.Net/MVC Developer (Oak Hill)
Source: RevolutionInsure
Details: Knowledge of C#, ASP.Net MVC, Azure and SQL Server with emphasis on writing modular, scalable code. Experience with start-ups, MVC migration, familiarity with...  More
7 days ago

Austin, TX 24-June-2016

Mid-Level Web Developer
Source: Valore Partners
Details: ASP.NET, ASP.NET MVC (3.0, 4.0 and 5.0), ASP.NET Web API, WCF, WPF. The Valore Partners team is comprised of crazy-smart Developers, Architects, Analysts,...  More
17 days ago

Tempe, AZ 13-June-2016

Sr. .Net Developer
Source: Indeed
Details: 5+ years of experience building applications utilizing the Microsoft stack (.Net framework, ASP.Net MVC Web Forms, Transact SQL, C#)....  More
7 days ago

Cleveland, OH 44115 23-June-2016

C# .Net Developer
Source: Indeed
Details: (Entity Framework, WCF, ASP.NET MVC)*. Proficient in developing web applications using Asp.NET MVC. Experienced with multi-tier application, design patterns and...  More
23 days ago

Pittsburgh, PA 08-June-2016

Sr..Net Developer
Source: spruceinfotech
Details: MVC. Experience with Microsoft .NET, ASP.NET MVC, API, WCF, and WF technologies. C#....  More
1 day ago

Harrisburg, PA 30-June-2016

F2F must - Sr. Net Developer with Angular/Node JS skills
Source: Indeed
Details: Net Developer with Angular/Node JS skills. 8 years of hands-on experience with Microsoft NET technologies:....  More
8 days ago

New York, NY 22-June-2016

Web Developer/Code Poet (C#, AspMvc, Polymer)
Source: Indeed
Details: Junior to Intermediate C#, ASP.net, MVC, SQL Server and a desire to learn. We are a progressive startup software company in Irving, TX looking for C# / ASP.MVC...  More
6 days ago

Irving, TX 24-June-2016

.NET Developer- Healthcare Exp.- Columbia, MD
Source: Indeed
Details: MVC:. Knowledge of ASP.NET MVC. _*Optomi in partnership with a leading Healthcare IT Solutions firm is seeking a .NET Developer....  More
24 days ago

Columbia, MD 06-June-2016

Senior Front End 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
16 days ago

Kirkland, WA 14-June-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
6 days ago

Kirkland, WA 25-June-2016

Lead/ Sr .Net Developer
Source: Indeed
Details: Experience in developing applications using ASP.NET MVC. Om Group is seeking a Sr....  More
30+ days ago

Reston, VA 28-April-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.