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

Junior .NET Developer
Source: Publishers Clearing House
Details: Windows Forms, WCF, ASP.NET, MVC. Publishers Clearing House (PCH), headquartered in Port Washington, NY (soon to be Jericho, NY!)....  More
14 days ago

Port Washington, NY 11050 12-April-2017

Senior .Net Developer
Source: Indeed
Details: Excellent server side development in ASP.NET, MVC, ADO.NET, LINQ, Web API, Windows Service and. We are looking for a strong, well rounded, self-motivated web...  More
4 days ago

Kingwood, TX 22-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
5 days ago

San Luis Obispo, CA 21-April-2017

.NET Software Engineer
Source: CCC Information Services Inc.
Details: Sr. .NET Developer Cerritos, CA CCC Information Services, Inc. CCC provides the technology, data and insight needed to help our customers make informed,  More
5 days ago

Cerritos, CA 21-April-2017

Junior .Net Developer
Source: MassMutual Financial Group
Details: Experience working with WPF, CSS, Classic ASP, Infragistics controls, and SharePoint a plus, but not required. Junior .Net Developer....  More
20 days ago

Charlotte, NC 06-April-2017

Senior .Net Developer (Full-Stack)
Source: Indeed
Details: 4+ years of C# .NET and ASP.NET MVC development. Design, develop, and deliver web application components for a distributed system....  More
8 days ago

Austin, TX 18-April-2017

.Net Develoer
Source: conrep
Details: Experience with ASP.NET MVC and Bootstrap. The candidate also will work on the new custom modules/web sites developed in ASP.NET MVC C# platform....  More
12 days ago

Harrisburg, PA 17112 13-April-2017

Senior.Net Web Developer
Source: Indeed
Details: MVC. Our client – an established yet growing eCommerce firm seeks an accomplished .Net developer to fill a key role in the development of public-facing web...  More
6 days ago

Springfield, PA 19-April-2017

Senior .NET Developer
Source: Indeed
Details: *U.S. Citizens and those authorized to work in the U.S. are encouraged to apply. We are unable to sponsor at this time.* *Job Description: Senior .NET  More
14 days ago

Bloomfield, MI 12-April-2017

Junior to Mid-level .Net Developer
Source: Indeed
Details: Experience with the MVC pattern for web development. US Citizens or Greencard that do not require a Visa Sponsorhip for Full-Time Employment*....  More
7 days ago

Englewood, CO 18-April-2017

Junior .NET Developer
Source: NIC
Details: MVC. In-depth experience with C#, ASP.NET and MVC. Junior .Net Developer Position....  More
30+ days ago

Baton Rouge, LA 23-March-2017

.NET Software Engineer (Front End or Back End)
Source: Indeed
Details: Full stack Engineers will also get to work on our Front End within a ASP.NET MVC + JavaScript environment....  More
9 hours ago

San Diego, CA 92122 26-April-2017

Junior .NET Web Developer
Source: Indeed
Details: 1+ years experience ASP.NET MVC. The Award Zone provides tools for organizations to provide highly-effective motivational programs, such as employee reward and...  More
14 days ago

Atlanta North, GA 11-April-2017

Senior Software Developer .NET ASP.NET MVC
Source: Indeed
Details: Build new applications with .Net (C#) & ASP.NET MVC – heavy focus on client web portal. Reporting to the Vice President, Technology, the Senior Software...  More
25 days ago

New York, NY 10006 31-March-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
8 days ago

Seattle, WA 98115 18-April-2017

Software Developer
Source: Indeed
Details: Experienced in ASP.NET MVC 5, CSS3, HTML5, JavaScript, JQuery, Knockout.js and AngularJs. This would be a managed service position:....  More
9 days ago

Seattle, WA 16-April-2017

.NET Software Engineer
Source: Shipbob
Details: We have opportunities to solve our clients needs with a wide variety of frameworks and platforms such as ASP.NET MVC, Azure SQL Server, Angular and many more....  More
20 days ago

Chicago, IL 06-April-2017

Software Development Engineer (.NET)
Source: Indeed
Details: Talentry is looking for a solid .net developer (c#, WCF, MVC, angular) with good communication skills who likes the idea of working in an environment that...  More
22 days ago

Irvine, CA 03-April-2017

Full stack .Net Mobile Application Developer
Source: Posh Technologies
Details: Visual Studio 2013+, C#, ASP.NET MVC 5 and Web API 2. 5+ years of working experience with C#, ASP.Net MVC, SQL Server, JavaScript....  More
5 days ago

Redmond, WA 21-April-2017

Software Engineer, Jr.
Source: Indeed
Details: HTML, HTML5, MVC, JavaScript, CSS, XML, SQL Server 2008/2014, Restful web services, AJAX, Testing Automation and OOD....  More
26 days ago

Phoenix, AZ 30-March-2017

Sitecore Developer
Source: Ursus Incorporated
Details: Solid experience with C#, ASP.NET, MVC, JavaScript, HTML5, CSS3, Razor. About the Role:....  More
19 hours ago

Sacramento, CA 95834 25-April-2017

Senior C#/.NET Full Stack Developer
Source: Graphic Products
Details: 3+ years demonstrated experience in ASP.NET MVC 4/5+. We are looking for a Senior Full Stack Developer responsible for the ongoing development and advancement...  More
30+ days ago

Beaverton, OR 97008 09-March-2017

Junior .NET Developer (no 3rd party candidates)
Source: Indeed
Details: Candidate must be clearable for a federal government public trust clearance; no third party candidates. *Responsible for developing and supporting .NET/C#  More
30+ days ago

Herndon, VA 16-March-2017

Front End Developer
Source: Indeed
Details: Microsoft ASP.NET MVC experience. Design, develop, and deliver front end web application components for a distributed system....  More
4 days ago

Annapolis, MD 21401 21-April-2017

.NET/C# Software Integration Engineer
Source: BlueVolt
Details: Solid programming experience with C#, WCF, Restful services using WEB API, and ASP.NET MVC. BlueVolt is growing....  More
29 days ago

Portland, OR 27-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.