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

        [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

Full-stack C#/.NET Developer
Source: Pinnacle Partners
Details: 5+ years’ experience with ASP.NET, MVC and Entity Framework. Pinnacle Partners is assisting our client in their search for a full-stack C#/.NET Developer....  More
29 days ago

Indianapolis, IN 46240 14-November-2017

Junior Web Application Developer
Source: Network Runners, Inc.
Details: Expertise in NET, C#, ASP.NET, Web Services, ASP.NET MVC, Web Forms, JQuery. Junior Web Applications Developer....  More
30+ days ago

Sterling, VA 20164 25-October-2017

A2614A - ASP.NET, T-SQL, MVC, C#, Javascript Developer
Source: Indeed
Details: ASP.NET MVC development using C# and Razor - Required - 4 Years. The candidate also will work on the new custom modules/web sites developed in ASP.NET MVC C#...  More
13 days ago

Harrisburg, PA 01-December-2017

.NET Web Application Engineer
Source: iVinci Health
Details: Experience with ASP.NET MVC framework. Well-funded startup in $420B growing market....  More
25 days ago

Lehi, UT 84043 18-November-2017

.NET Web Application Engineer
Source: iVinci Health
Details: Experience with ASP.NET MVC framework. Well-funded startup in $420B growing market....  More
25 days ago

Boise, ID 83702 18-November-2017

Junior Full Stack NET Developer
Source: Indeed
Details: Proficiency in C# and .NET Framework (ASP.NET MVC, ASP.NET WebForms, Razor). Infobase Holdings has an immediate opening for a *Junior .NET Web Developer*....  More
30+ days ago

New York, NY 10001 06-October-2017

Senior Software Engineer, .net, MVC
Source: Indeed
Details: Experience in MVC, preferably ASP.NET MVC 4. Alteso is looking to add a developer to our technology team building cutting edge software for the Auto Re...  More
30+ days ago

Trevose, PA 19053 17-August-2017

Senior Backend .Net Web Developer
Source: Indeed
Details: Experience with C#, ASP.NET MVC, REST, ORMs and JSON. Senior Backend .Net Web Developer*....  More
30+ days ago

Overland Park, KS 06-November-2017

Junior ASP.Net C# Developer
Source: Career Evolutions
Details: Classic ASP (for conversion of legacy applications). 1 to 3 years of ASP.NET, MVC and C# experience. Career Evolutions is looking for an Junior ASP.Net C#...  More
26 days ago

Scottsdale, AZ 85258 17-November-2017

Junior Web Developer
Source: Indeed
Details: Experience with C#, .Netframework (4.5+), Asp.Net , MVC, WPF. This role is responsible for coding, modifying, and supporting a custom built e-commerce platform,...  More
30+ days ago

Fall River, MA 01-November-2017

.NET Applications Developer 3
Source: Metropolitan Council
Details: Experience with any JavaScript based MVC or MVVM framework, such as:. Work in an environment that allows you to have a life outside of work and does NOT require...  More
30+ days ago

Minneapolis, MN 07-October-2017

Senior .NET Developer- US Citizenship required
Source: Indeed
Details: Experience developing and implementing software solutions using .NET Framework, C#, SQL, ASP.NET, MVC, JSON, JavaScript, and IIS....  More
30+ days ago

Fairfax, VA 26-September-2017

.Net Software Engineer
Source: Trek Bicycle
Details: Experience with Windows Azure, ASP.NET MVC, and ORM tooling required. Our mission is to create products we love and take care of our customers....  More
30+ days ago

Waterloo, WI 53594 16-October-2017

Senior Software Engineer .NET & SQL Server
Source: Indeed
Details: .NET Desktop Application Programming (C#, WinForms, MVC). Full-Time W2 direct position in Waltham, MA*....  More
30+ days ago

Waltham, MA 02451 02-November-2017

Independent Freelance Senior Developer for ASP.NET MVC SaaS App
Source: Indeed
Details: This project includes the design, programming and testing of a security focused ASP.Net MVC web based application with various back end systems including an...  More
14 days ago

Great Neck, NY 11021 29-November-2017

Senior .Net Developer
Source: Indeed
Details: Asp.Net, MVC, Entity Framework, LinQ, WCF:. Utilize established development tools, guidelines and conventions including but not limited to C#, ASP .Net, ADO.Net...  More
2 days ago

Irvine, CA 12-December-2017

Senior .Net Developer
Source: Indeed
Details: Experience in ASP.net MVC. Please apply with updated resume with 1099 /W2 rates to *Lakshmi at the sriiusa.com*....  More
15 days ago

Phoenix, AZ 28-November-2017

Senior .Net Developer
Source: Indeed
Details: .NET, MVC, WebAPI, SQL:. _Strong experience with MVC, WebAPI and Webforms._*. .Net Framework 5.0/4.5/4.0/3.5, ADO.NET, ASP.NET MVC, Entity Framework , LINQ, Web...  More
30+ days ago

Marlborough, MA 28-September-2017

.NET Developer
Source: Professional Technology Integration, Inc.
Details: ASP .NET MVC 3.0 OR HIGHER (Required 3 Years). ASP .NET 3.5 OR HIGHER (Required 3 Years). Local candidates strongly preferred....  More
10 hours ago

Richmond, VA 13-December-2017

.NET Developer
Source: Planet Risk
Details: ASP.NET MVC, JQuery, AngularJS and ReactJS. Experience working in a MVC or MVVM architecture pattern. Work with colleagues to design, build, and test web...  More
5 days ago

United States 08-December-2017

.NET Developer
Source: eimagine
Details: Design, deploy and debug ASP. Ability to design, develop, test, implement and maintain C# and VB .NET, ASP.NET MVC web applications and web services with SQL...  More
30+ days ago

Indianapolis, IN 16-October-2017

ASP.NET Web Developer
Source: Indeed
Details: C# and ASP.NET MVC programming:. Develop new ASP.net MVC applications conforming to the design specifications provided....  More
30+ days ago

Orlando, FL 08-November-2017

Senior Full Stack .NET Developer
Source: Indeed
Details: Comprehensive skills in ASP.NET MVC, JavaScript, and RESTful web services. Why ARC Healthcare Technologies?*....  More
11 hours ago

Lake Orion, MI 13-December-2017

Senior Full Stack .NET Developer
Source: Indeed
Details: Experience in ASP.NET Web Forms, MVC, WebAPI or WPF development (5+ years). To be successful the ideal candidate must have a background in ASP.NET MVC, C#, VB...  More
11 days ago

Chatsworth, CA 91311 02-December-2017

C# Engineer for an IoT Smart Energy Company (ASP.NET, MVC, Angular, SQL)
Source: Indeed
Details: 6+ years of full stack C#/.NET MVC experience. Strong server-side developer skills in .NET Framework and ASP.NET Development (C#), MVC, Web API, MS SQL Server...  More
30 days ago

Irvine, CA 13-November-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 www.webdevelopmenthelp.net, www.topwcftutorials.net, and www.sharepointfordummies.net.