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: ASP.NET MVC, Entity Framework:. 3-5+ years of experience designing complex web applications in ASP.NET MVC, Entity Framework....  More
10 days ago

Redmond, WA 20-April-2017

Software Developer (Jr/Mid)
Source: Blue Canopy
Details: ASP.NET MVC and Web Forms, SQL Server, Visual Studio, TFS, C#, HTML, CSS, JavaScript. Blue Canopy Group, LLC is seeking a Software Developer (Jr/Mid) for our...  More
3 days ago

Fort Meade, MD 27-April-2017

Jr. Front End Angular 2 Developer
Source: Phenomenex
Details: Experience with ASP.NET MVC, REST Services. The right candidate will have a passion for software development, good communication skills, and the ability to...  More
5 days ago

Torrance, CA 90501 25-April-2017

Web Developer
Source: BoatUS
Details: ASP. BoatU.S., a part of GEICO and the Berkshire Hathaway family of companies, is looking for a Web Developer at our Headquarters in Alexandria, VA....  More
2 days ago

Alexandria, VA 28-April-2017

.NET Full Stack Developer
Source: Indeed
Details: .NET / ASP.NET / MVC development environment:. Candidates should have full stack experience for ASP.NET MVC Web Development in particular....  More
5 days ago

Cerritos, CA 90703 25-April-2017

Jr. Software Developer
Source: Ellie Mae
Details: Familiarity with ASP.NET MVC and/or .NET Web API a plus. Ellie Mae is a provider of enterprise on-demand solutions, including an online network, software and...  More
10 days ago

Pleasanton, CA 94588 19-April-2017

Web Developer
Source: Indeed
Details: Experience with bootstrap, ASP.NET MVC a plus. Expertise in front-end web development • Proficiency with HTML, CSS, javascript, Angular.js • Experience with...  More
30+ days ago

Redmond, WA 23-March-2017

Web Developer
Source: Indeed
Details: The National Fire Protection Association’s mission is to help save lives and reduce loss with information, knowledge and passion. An international nonprofit  More
16 days ago

Quincy, MA 14-April-2017

.NET Software Developer (Jr/Mid)
Source: Blue Canopy
Details: ASP.NET MVC and Web Forms, SQL Server, Visual Studio, TFS, C#, HTML, CSS, JavaScript. Blue Canopy Group, LLC is seeking a .Net Software Developer (Jr/Mid) for...  More
22 days ago

Fort Meade, MD 08-April-2017

Full Stack .Net Developer
Source: Indeed
Details: Candidates should have full stack experience for ASP.NET MVC Web Development in particular. Cypress North Corp, a leading software engineering and digital...  More
23 days ago

Buffalo, NY 14210 06-April-2017

Software Engineer .NET, C#
Source: American College of Healthcare Executives
Details: Utilize ACHE’s evolving technology stack including Visual Studio, C#, MS SQL Server, ASP.NET, MVC, XML/XSLT, JavaScript, and jQuery....  More
4 days ago

Chicago, IL 60606 26-April-2017

Creative Full-Stack ASP.Net Developer
Source: Indeed
Details: Minimum 3-5yrs ASP.Net MVC (C#) web development experience “Full-Stack” preferred:. Understanding of C#, MVC, HTML, Javascript, CSS, Entity Framework, SQL...  More
27 days ago

Denver, CO 03-April-2017

Jr. .Net Developer - TS/SCI
Source: LongView International Technology Solutions Inc.
Details: Strong knowledge of Visual Studio 2013, Team Foundation Server, ASP.Net MVC, Angular 1.7, Bootstrap v3, WebAPI , LINQ,....  More
30+ days ago

Fort Belvoir, VA 29-March-2017

Mobile Application Developer
Source: Indeed
Details: Proficient in writing Web API (ASP.NET MVC WebAPI, EF6.0). Prior experience in Hybrid web application development using ASP.NET MVC, and client frameworks like...  More
3 days ago

Charlotte, NC 26-April-2017

Web Developer
Source: GenConnect Recruiting and Consulting
Details: Solid understanding of Microsoft ASP.Net MVC 5 and Microsoft ASP.Net Web Api 2. Are you interested in joining a company that will map out your development...  More
27 days ago

Atlanta, GA 03-April-2017

Senior ASP.NET Developer
Source: Brogden Enterprises, Inc.
Details: Experience working with ASP.NET MVC and nHibernate. Member of the programming team responsible for the design, development and enhancement of websites....  More
9 days ago

Aberdeen, MD 21-April-2017

Senior ASP.NET Developer
Source: Brogden Enterprises, Inc.
Details: Experience working with ASP.NET MVC and nHibernate. Member of the programming team responsible for the design, development and enhancement of websites....  More
9 days ago

Huntsville, AL 21-April-2017

Software Engineer C#/ASP.NET MVC/JavaScript
Source: Cormant, Inc.
Details: You will be working on full stack development including Marionette client, and a C# MVC architecture with NHibernate/RDBMS as the back-end....  More
9 days ago

San Luis Obispo, CA 21-April-2017

Web Developer
Source: Hubert
Details: Experience with any modern MVC web architecture (ASP.NET MVC, Ruby/Rails, Django/Python, etc.). Programmer, web programmer, web development, MVC web...  More
27 days ago

Harrison, OH 45030 03-April-2017

Senior ASP.NET MVC Developer
Source: Indeed
Details: 4+ years experience developing web applications using ASP.NET MVC. The successful candidate provides great interpersonal and communication skills coupled with...  More
10 days ago

Lake Orion, MI 20-April-2017

Sr. C#/ASP.NET Developer
Source: Logic20/20
Details: *Strong C#, .NET framework (ASP.NET MVC, Entity Framework), jQuery, HTML 5 development Qualifications. Logic20/20 is a Seattle based Management & Technology...  More
12 days ago

Seattle, WA 98115 18-April-2017

SQL Report Developer (N. Pittsburgh)
Source: Indeed
Details: Experience with ASP.NET MVC is a plus. Please no contractors, local candidates only....  More
1 day ago

Pittsburgh, PA 29-April-2017

Application Developer
Source: Indeed
Details: MVC:. Microsoft.Net Framework 4.0 and higher, C#, ASP.Net, MVC, WebAPI, Javascript, AJAX, JSON. Franklin based technology consulting firm is recruiting a .Net...  More
13 days ago

Franklin, TN 37067 17-April-2017

Full Stack .NET Developer
Source: Forte Group
Details: Experience with ASP.NET, MVC and .NET Framework; One of the largest technology providers is currently looking for a Full Stack .NET Developer to join their team...  More
30+ days ago

Chicago, IL 60606 23-March-2017

Full Stack .Net Developer with MS dynamics
Source: Indeed
Details: (SDE with C#/ASP.Net/MVC, SQL Server, etc. - Microsoft stack) ~ Experience working with PCI compliant systems - examples: great plains or MS Dynamics  More
30+ days ago

Seattle, WA 02-March-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.