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

Web Developer
Source: Indeed
Details: Have worked with the .NET web stack including ASP.NET, MVC, WebAPI 2 and C#. We are seeking a driven, innovative and detail-obsessed software developer who...  More
22 hours ago

Bellevue, WA 06-December-2016

Web Developer (C# & AngularJS) -2 months of contract
Source: CSI Interfusion Inc
Details: Solid skills on C#, ASP.Net, MVC, JavaScript, CSS, HTML, etc. CS I Interfusion ( CSI ) (size:....  More
5 days ago

Redmond, WA 02-December-2016

Backend Web Developer
Source: Indeed
Details: Minimum 4 years experience with writing WinAPI/RESTFul API and working in an ASP.NET MVC environment. Keyventer is seeking a *Back End Web*....  More
8 days ago

Seattle, WA 28-November-2016

Web Developer (C# & AngularJS) - 2 months
Source: Indeed
Details: *CS* *I Interfusion* ( *CSI* ) (size: 20,001+ employees, globally), a leading global provider of *IT consulting services, technical services* and *outsourcing...  More
14 days ago

Redmond, WA 23-November-2016

Programmer / Analyst
Source: Intel
Details: Advanced forms with dynamic connection to stored procedures on other databases - Experience in database design and data modeling - Experience with developing...  More
5 days ago

Hillsboro, OR 97124 02-December-2016

Programmer Analyst
Source: AIG
Details: Strong knowledge of .Net Framework, C#, ASP.Net, MVC, LINQ, Visual Studio 2008/2010/2013 and Version Control System (TFS, Git etc.)....  More
30+ days ago

Jeffersonville, IN 16-September-2016

Web Application Developer
Source: Indeed
Details: ASP.NET MVC, Web Forms, Web API. SC Strategic Solutions is looking for passionate full time software developers who are efficient problem solvers with a...  More
14 days ago

Norwalk, OH 23-November-2016

Web Developer
Source: Indeed
Details: MVC:. ASP.Net MVC and C#.Net experience a must*. ~~~~~NOT A REMOTE POSITION~~~~~*....  More
14 days ago

Sarasota, FL 34232 23-November-2016

Front End Developer | Web Mobile
Source: Specialists On Call
Details: AngularJS, HTML5, Sass, C#, ASP.Net MVC, SOA. Specialists On Call, Inc....  More
15 days ago

Reston, VA 20190 21-November-2016

Microsoft web developer - Contract - Telecommuting
Source: Indeed
Details: MVC, .Net, CSS, HTML:. Working familiarity with ASP.net, MVC. This is a 3 months + contract position for our direct client based in San Antonio....  More
18 days ago

San Antonio, TX 19-November-2016

.NET Developer Instructor
Source: Indeed
Details: NET – You are comfortable working with ASP.NET, MVC and Core Web API. About Coder Camps:....  More
19 hours ago

Redmond, WA 07-December-2016

e-Commerce Web Developer
Source: Indeed
Details: Hands-on code development experience in web development field using ASP.NET MVC, C#, HTML 5.0, jQuery, XML, CSS, and Web Services....  More
21 days ago

South Saint Paul, MN 55075 16-November-2016

Back-End Web Developer
Source: DNTG Software
Details: Experiences with ASP.NET and MVC in C#, Web API. Develop and maintain secure and stateless web services using Microsoft ASP.NET MVC 4.0 based on the REST...  More
21 days ago

Buena Park, CA 16-November-2016

Web & Mobile Developer
Source: Indeed
Details: Our software stack includes Xamarin C# on iOS & Android, ASP.NET MVC, Microsoft Azure, Angular.js, HTML5, and JavaScript....  More
21 days ago

Kent, WA 15-November-2016

.Net Developer with Azure Cloud Experience
Source: CSI Interfusion Inc
Details: Demonstrated experience working on services built using ASP.NET / MVC, and SQL db. CSI Interfusion (CSI) (size:....  More
5 days ago

Redmond, WA 02-December-2016

Senior Software Engineer
Source: Clarity Consulting Inc.
Details: C# / WinRT / .NET / XAML / Windows 8/8.1 / Windows Phone 8/8.1 / Xbox / UCMA/UCWA / iOS / Cocoa Objective-C / Android / Xamarin / HTML5 / JavaScript/jQuery /...  More
1 day ago

Seattle, WA 06-December-2016

.Net Developer
Source: Indeed
Details: .Strong Experience developing MVC applications using ASP.Net MVC. .4+ years experience in software engineering....  More
7 days ago

Redmond, WA 30-November-2016

Web Developer
Source: Indeed
Details: Experience with ASP.NET MVC is a plus. R+L Carriers is currently seeking a Web Application Developer for our Ocala, FL Technical Center and our Wilmington, OH...  More
29 days ago

Wilmington, OH 45177 08-November-2016

.Net Developer
Source: Indeed
Details: .Strong Experience developing MVC applications using ASP.Net MVC. Essential Job Functions....  More
42 minutes ago

Seattle, WA 07-December-2016

Front-End Web Developer
Source: Indeed
Details: Experience with the MS development stack Visual Studio, .NET, ASP.NET MVC, etc. Crystal Capital Partners, a financial services company w/ over 20 years of...  More
30+ days ago

Miami, FL 04-November-2016

Web Applications Developer
Source: ITR (Information Technology Resources)
Details: Experience with the MVC pattern and responsive design of web applications. Web Applications Developer....  More
30+ days ago

Oak Ridge, TN 02-November-2016

Web Developer
Source: Indeed
Details: Experience with ASP.NET MVC is a plus. R+L Carriers is currently seeking a Web Application Developer for our Ocala, FL Technical Center and our Wilmington, OH...  More
29 days ago

Ocala, FL 08-November-2016

Senior Developer
Source: Indeed
Details: .NET architecture, ASP.NET MVC, OOP, SOA, repository patterns (CRUD). Development, maintenance and administration as part of a team supporting advanced...  More
2 hours ago

New York, NY 07-December-2016

Senior Software Developer
Source: MediaRadar
Details: Knowledge of ASP.NET MVC 4/5. Web based projects will center on ASP.Net MVC 4 and the Razor view engine, with Angular.js....  More
20 days ago

New York, NY 17-November-2016

Programmer Analyst
Source: Kindred Healthcare
Details: Have experience with ASP.NET MVC and/or WPF. Clinical Systems Development....  More
19 days ago

Louisville, KY 40202 18-November-2016
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest
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.