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

Full Stack Developer
Source: Indeed
Details: ASP, ASP.NET, *ASP.NET MVC*. Sharenet has Information Management infrastructure that requires monitoring, management, and incremental updates....  More
8 hours ago

Jacksonville, FL 28-September-2016

Full Stack Developer
Source: Indeed
Details: Develop UI components using technologies such as ASP.NET MVC, JavaScript, React.js, JQuery. 5+ years of experience using web technologies including ASP.NET MVC,...  More
5 days ago

Philadelphia, PA 23-September-2016

Software Developer
Source: Indeed
Details: MVC:. Experience with ASP.NET MVC and the .NET Framework. The project will be implemented with cutting-edge Web and cloud-based technologies, using SCRUM...  More
1 day ago

Redmond, WA 27-September-2016

XML Application Developer
Source: Indeed
Details: Microsoft MVC Framework from versions 1 to 3. Designs, develops and implements new methods and procedures of the technical solution that meets the requirements...  More
1 day ago

Aberdeen Proving Ground, MD 27-September-2016

Application Developer (Secret Clearance)
Source: Indeed
Details: *Overview* Are you looking for an opportunity to join a growing company that is innovative, cutting edge, and mission centered? Our prestigious technical and  More
3 days ago

Arlington, VA 25-September-2016

Application Developer
Source: Indeed
Details: 3+ years of development experience using Microsoft IIS, C#, ASP.NET, MVC, VB, NET, XML and SQL Server. Jefferson Capital Systems, LLC is an industry-leading...  More
7 days ago

Saint Cloud, MN 56303 21-September-2016

Application Developer
Source: Indeed
Details: ASP.NET, ASP.NET MVC, MS SQL Server, HTML, CSS, JavaScript, C#/VB.NET and Microsoft development stac:. Minimum 3 years’ experience with established development...  More
7 days ago

Miami, FL 21-September-2016

Application Support/Net Developer
Source: Indeed
Details: *JOB DESCRIPTION: * Mascot Media is seeking an individual to join our Application Development and Support Team and contribute to the enormous growth of our  More
7 days ago

Fayetteville, AR 20-September-2016

Application Developer
Source: Indeed
Details: Working knowledge of C#, ASP.NET, MVC, and Visual Studio. We have an opening for a dynamic Application Developer who is passionate about what they do and...  More
8 days ago

Cranston, RI 19-September-2016

Application Developer
Source: Indeed
Details: HTTP, AJAX, HTML5, ASP.NET WebForms, ASP.NET MVC, MVVM, JavaScript/jQuery and CSS3. Long term consulting assignment over two years....  More
13 days ago

Phoenix, AZ 15-September-2016

Software Developer
Source: Indeed
Details: ASP.NET MVC experience is required. Build and maintain application functionality for new and existing systems.Participate in all aspects of the software...  More
19 days ago

Rancho Cordova, CA 08-September-2016

Software Developer
Source: Indeed
Details: C#, SQL, HTML, CSS, JSON, JavaScript, ASP.NET Web Forms, ASP.NET MVC, Visual Studio. Does this describe you?*....  More
5 days ago

Miamisburg, OH 45342 23-September-2016

Mobile Application Developer
Source: Indeed
Details: HTTP, AJAX, HTML5, ASP.NET WebForms, ASP.NET MVC, MVVM, JavaScript/jQuery and CSS3. Mobile Application Developer....  More
14 days ago

Phoenix, AZ 14-September-2016

Software Developer (Early Career)
Source: Indeed
Details: Working knowledge of WinForms, MVC, and entity framework. Web Programming experience with JavaScript, Ajax, JQuery, HTML, ASP.NET, MVC, responsive design....  More
5 days ago

Fargo, ND 58104 22-September-2016

Software Developer Internship
Source: Arbiter Sports
Details: 0-1 year software development experience or academic exposure in developing web applications using ASP.NET MVC, C#, SQL Server and Entity Framework....  More
7 days ago

Sandy, UT 84070 21-September-2016

Software Developer w/experience
Source: Indeed
Details: 1 year ASP.net MVC experience preferred. Some experience developing Web applications using ASP.net MVC. Develop custom applications in Visual Studio’s VB.Net/C#...  More
9 days ago

Louisville, KY 19-September-2016

Software Developer
Source: Indeed
Details: The Software Developer must have knowledge of Microsoft technologies, including Microsoft .NET 4.0/4.5, C#, ASP.NET MVC, WebApi, IIS, Entity Framework, SQL...  More
15 days ago

Chesapeake, VA 13-September-2016

Software Developer Intern
Source: Health Catalyst
Details: Job Title: SoftwareDeveloper/Test Intern Department: Product Development Classification: Intern Status: Full-time (40 hours/week) Location: Salt Lake City  More
16 days ago

Salt Lake City, UT 12-September-2016

Software Developer
Source: NuGrowth Solutions
Details: The ideal candidate will be fluent in C#, ASP.NET MVC, SQL Server and Web Service Architecture. SIS, a leading provider of Agency Management Systems for...  More
18 days ago

Columbus, OH 43228 10-September-2016

Programmer I
Source: Indeed
Details: The North Texas Behavioral Health Authority (NTBHA) is a Local Behavioral Health Authority based in Dallas, Texas. It is responsible for developing a  More
13 days ago

Dallas, TX 15-September-2016

MVC Entity Framework Azure Developer
Source: Indeed
Details: MVC:. Experience with ASP.NET MVC and the .NET Framework. The project will be implemented with cutting-edge Web and cloud-based technologies, using SCRUM...  More
8 days ago

Redmond, WA 20-September-2016

Junior Software Developer
Source: Indeed
Details: Net MVC, C#, VB.Net, SQL Server, Visual Studio, and Web Services. Junior Software Developer*....  More
20 days ago

Irving, TX 08-September-2016

Software Developer
Source: Indeed
Details: *Software Developer* *_Please do not apply if you are not legally authorized to work in the United States without an employer-sponsored petition for a visa,  More
20 days ago

Bath, MI 48808 08-September-2016

Dot Net Application Developer
Source: Indeed
Details: Participate in developing new sites using ASP.NET MVC Framework. Microsoft .NET Application Developer....  More
30 days ago

Fairfax, VA 29-August-2016

Software Developer
Source: Indeed
Details: AngularJS and Kendo UI, Asp.Net MVC, ASP.Net Web API and C#. BBK Worldwide, a first-of-its-kind marketing consultancy specializing in global patient recruitment...  More
22 days ago

Needham, MA 06-September-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.