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

C# Developer
Source: Posh Technologies
Details: 5+ years of working experience with C#, ASP.Net MVC, SQL Server, JavaScript. 10+ years of Software development experience with strong background in computer...  More
8 days ago

Redmond, WA 22-May-2016

C# Developer
Source: Diverse Lynx
Details: ASP.NET MVC, AngularJS. We need a strong developer having following skills:....  More
10 days ago

Redmond, WA 20-May-2016

C# .Net Developer
Source: Macropace Technologies
Details: Strong in MVC Frameworks. 6+ years of experience working with Microsoft .NET, ASP.NET, C#, application frameworks such as ASP.NET MVC, JQuery, Entity Framework,...  More
2 days ago

Dallas, TX 28-May-2016

C# ASP.Net Developer(Local candidates only)- Itasca, IL-W2
Source: Indeed
Details: Telerik ASP.NET MVC Controls). Classic ASP knowledge We need a detail oriented individual with full SDLC experience and the ability to communicate in written...  More
2 days ago

Itasca, IL 27-May-2016

.NET UI Developer (ASP.NET – MVC – C#)
Source: Indeed
Details: MVC (prefer version 5). Focus on front end UI support utilizing MVC, JQuery, CSS3, HTML5, and Bootstrap. American Computer Services, Inc....  More
4 days ago

Des Moines, IA 25-May-2016

C# .Net Developer
Source: Indeed
Details: Excellent knowledge ASP.NET MVC. _*_Candidates will also have to take a code test_*_*....  More
5 days ago

Wilton, CT 24-May-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
26 days ago

Des Moines, IA 03-May-2016

C# Developer
Source: JPMorgan Chase
Details: Minimum 6 years development background using C#, WCF, ASP.NET, MVC, WPF, T-SQL, IIS. JPMorgan Chase & Co....  More
30+ days ago

Houston, TX 17-February-2016

C# .Net Developer
Source: Indeed
Details: ASP.NET MVC (Highly desired)Linq to SQLSQL Server 2008Git\\BitBucketSSIS. Vivid Pages is currently looking for a C# .NET Developer for the support and...  More
6 days ago

Tysons Corner, VA 23-May-2016

C# .Net Developer
Source: Indeed
Details: Proven experience with Microsoft .NET technologies including, ASP.NET MVC 4/5, Entity Framework 6. JOB DUTIES & RESPONSIBILITIES:....  More
11 days ago

Alpharetta, GA 18-May-2016

Full Stack C# .NET Developer
Source: Indeed
Details: - Strong knowledge of common design patterns including MVC and MVVM. - Several years of experience creating enterprise applications using C#, ASP.NET MVC, .NET...  More
12 days ago

Oldsmar, FL 18-May-2016

C# .Net Developer
Source: Indeed
Details: Create and support web based applications with ASP.NET, MVC, Web Forms, WCF, HTML, CSS, JavaScript, jQuery and other client-side scripting technologies....  More
12 days ago

Charlotte, NC 17-May-2016

Technical Lead Web Developer
Source: Earth Networks
Details: 7+ years of experience using Microsoft stack (C#, ASP.NET, MVC, SQL Server, etc.). Earth Networks, owner of the WeatherBug brand, is seeking a Technical Lead...  More
30+ days ago

Germantown, MD 11-April-2016

C# ASP.NET MVC JavaScript Developer / Architect
Source: Indeed
Details: C# ASP.NET MVC JS HTML5:. We are a financial software company looking for a talented, motivated contract or contract-to-hire C# ASP.NET MVC JavaScript Developer...  More
18 days ago

Houston, TX 11-May-2016

C# .Net Developer *Mandarin speaker
Source: Indeed
Details: ASP.NET/MVC, HTML, Ajax, JQuery, JSON, JavaScript, XML/XSLT, CSS, NET 3.5/4.0/4.5. \*\*Mandarin Chinese proficiency required\*\*....  More
19 days ago

Chicago, IL 11-May-2016

Application Developer (.Net/C#/SQL Server)
Source: Indeed
Details: Net development skills*. C# 4.0, ASP, net/MVC, . NET framework 4.0 and above)*. Required/Desirable:....  More
24 days ago

New York, NY 05-May-2016

Junior C#/ASP.Net/MVC Developer - 3 months+ (Fairfield, NJ)
Source: Indeed
Details: Experience with MVC, Xamarin, Telerik, SSIS is a plus. Junior C#/ASP.Net Developer - 3 months+ Contract*....  More
30+ days ago

Fairfield, NJ 28-April-2016

Sr. .NET
Source: Apex Systems Inc
Details: Job #: 665919 VERY IMMEDIATE NEED! One of our clients needs an additional hand on deck to complete an application rollout by Aug 1st! They need you to start  More
3 days ago

Nashville, TN 26-May-2016

ASP.Net MVC and C#.Net Developer
Source: Indeed
Details: MVC:. Net MVC and C#.Net experience a must*. \*\*\*\*\*Only Local Candidates considered\*\*\*\*\**....  More
30+ days ago

Sarasota, FL 34232 22-April-2016

Sr .NET
Source: Apex Systems Inc
Details: Candidates must have experience with ASP.net MVC and C# as well as having some enterprise service bus experience. Job #:....  More
6 days ago

Kissimmee, FL 24-May-2016

Software Developer
Source: Indeed
Details: *Software Developer* *U-Haul Corporate Headquarters* *Phoenix, AZ* *Description: * The U-Haul IT team is looking for a Software Developer needed for a...  More
3 days ago

Phoenix, AZ 85004 26-May-2016

Software Developer - Front End
Source: Indeed
Details: *U-Haul International* *Phoenix, AZ* *Software Developer - Front End* *Description: * U-Haul Software Development team is looking for a Front-End Software  More
3 days ago

Phoenix, AZ 85004 26-May-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
24 days ago

Kirkland, WA 06-May-2016

Web Developer
Source: Indeed
Details: Software developer with proven experience in C#, ASP.NET, MVC, SQL, web application development. This is a UI and Backend – Web development position who has...  More
4 days ago

Redmond, WA 25-May-2016

Software Developer
Source: Indeed
Details: .NET platform – including C#, ASP.NET, MVC, Web API, and Entity Framework. This is made up of a number of systems ranging from front-end websites to backend...  More
24 days ago

Seattle, WA 05-May-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.