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

SharePoint Developer (Remote)
Source: Indeed
Details: *Role - SharePoint Developer* *Location - Seattle, WA* *Employment - Full Time (Remote)* *Any VISA is OK but need ready to relocate ASAP.* *Experience* *  More
30+ days ago

Seattle, WA 08-May-2016

Full Stack .Net Developer
Source: Indeed
Details: Visual Studio 2015, SQL Server 2008+ architectural, .NET 4/4.5 FCL, C# language and syntax, SQL, ASP:. Visual Studio 2015, SQL Server 2008+ architectural, .NET...  More
15 days ago

Redmond, WA 16-August-2016

.Net Developer
Source: Indeed
Details: ASP.NET MVC 4.0, C# .Net, Azure Storage, Web API, Angular JS, VSO, TFS:. Excellent in ASP.NET MVC 4.0 and above, C#.NET 4.0 above, MS-SQL Server, WCF....  More
21 days ago

Redmond, WA 10-August-2016

Software Developer
Source: Indeed
Details: Experience with .Net/C#, ASP.NET MVC, JavaScript, JQuery, WPF, XML, SQL Server, LINQ, Entity Framework, WCF....  More
3 hours ago

Rancho Cucamonga, CA 91730 31-August-2016

C# .NET Full Stack Developer
Source: Indeed
Details: ASP.NET MVC and Web API server development. The ideal candidate has excellent software skills, is self-motivated, and thrives in a flexible work environment....  More
9 hours ago

Atascadero, CA 93422 31-August-2016

Software Developer
Source: Indeed
Details: ASP.NET, MVC, C#, VB.NET, HTML, jQuery, Cloud:. Design, code, test, and analyze software programs and applications....  More
12 hours ago

San Juan, PR 31-August-2016

Computer Network Support Specialist & Developer
Source: Indeed
Details: Web Languages, HTML, JavaScript, ASP Classic, LAN/WAN Troubleshooting, ASP.NET MVC, Computer Networking, Teach-Ability, MS SQL, CSS....  More
14 hours ago

Lincoln, ME 31-August-2016

Senior Software Engineer
Source: Microsoft
Details: We provide REST APIs via ASP.NET MVC, and we use jQuery, Knockout.js, and other modern frameworks to build our user interface....  More
4 days ago

Redmond, WA 98052 27-August-2016

.NET Developer
Source: Nexient
Details: Strong experience in object oriented design & development, Design Patterns, Multi-threading, OOAD Experience in C# and ASP.NET, including ASP.NET MVC....  More
21 hours ago

Ann Arbor, MI 31-August-2016

Ruby on Rails Developer
Source: Indeed
Details: ASP.NET, MVC, C#, SQL, SSRS, Ruby on Rails, Agile. Client Resources Inc*....  More
1 day ago

Omaha, NE 30-August-2016

.NET Developer
Source: Indeed
Details: .NET, MVC, Windows Forms, SQL Server, Entity Framework:. VB.NET, C#, ASP.NET MVC, WCF, DHTML, XML, JSON and SQL, HTML5, and JavaScript. MITEC Solutions Inc....  More
1 day ago

Westland, MI 30-August-2016

Software Engineer - .Net Developer
Source: Valence Health
Details: 2-3 years of experience developing web applications using ASP.NET MVC. Valence Health provides value-based care solutions for hospitals, health systems and...  More
7 days ago

Chicago, IL 24-August-2016

.NET developer-Need only Locals in Texas
Source: Indeed
Details: C#, ASP.NET MVC, Windows IIS7, Visual Studio 2015Back end:. They are looking for someone that has 2-4 years of experience as a developer....  More
1 day ago

Dallas, TX 30-August-2016

Microsoft Developer | .NET
Source: CareWorks Tech
Details: Primary Responsibilities: Translate business requirements into technical solutions. Participate in design sessions with other Developers, Business Analysts,  More
2 days ago

Columbus, OH 29-August-2016

.Net Developer
Source: Indeed
Details: Utilize established development tools, guidelines and conventions including but not limited to ASP.NET, MVC Framework, SQL Server, HTML, CSS, JavaScript, and C#...  More
2 days ago

Baltimore, MD 29-August-2016

CMS Developer with strong .NET
Source: RDA Corporation
Details: Three+ years’ development experience using C#, ASP.NET, MVC and SQL technologies. We are currently seeking a senior software engineer to join our Washington DC...  More
2 days ago

Washington, DC 29-August-2016

Back End Developer
Source: Pietech, Inc
Details: C#, ASP.Net MVC, SQL Server, JavaScript, NHibernate. Is currently looking for a Software Developer in Richmond, VA....  More
2 days ago

Powhatan, VA 23139 29-August-2016

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

Fairfax, VA 29-August-2016

C# .Net Developer
Source: Indeed
Details: ASP.NET MVC 4.0:. Excellent in ASP.NET MVC 4.0 and above, C#.NET 4.0 above, MS-SQL Server, WCF. We have C# role on Aricent FT....  More
28 days ago

Redmond, WA 03-August-2016

.NET/PHP Developer
Source: Indeed
Details: MVC frameworks (such as CakePHP and ASP.NET MVC). Want variety and challenge?...  More
9 hours ago

Canton, OH 44718 31-August-2016

Software Developer
Source: Indeed
Details: ASP.NET, Web Services, and Windows Services, experience with MVC, experience with web technologies:. The main areas of responsibility include helping with the...  More
5 days ago

Franklin, OH 45005 26-August-2016

.Net Developer
Source: Indeed
Details: MVC. We are looking for a few well rounded developers to help with our .Net web development applications....  More
5 days ago

Carrollton, GA 30117 26-August-2016

Full Stack .Net MVC developer
Source: Indeed
Details: Net MVC (P3/P4). Full Stack .Net MVC developer*. Greetings for the day!...  More
5 days ago

Sunnyvale, CA 26-August-2016

.Net Developer
Source: Indeed
Details: ASP.NET MVC, ASP.NET,C#, C++, Object Oriented Programming, T-SQL, JAVA, Javascript. Two years or more experience in the following technologies:....  More
5 days ago

San Juan, PR 00926 26-August-2016

Enterprise Developer
Source: Indeed
Details: Design and develop ASP.Net MVC applications written in C#, HTML, and JavaScript. At least 2 years of experience in developing applications in C# using ASP.Net...  More
5 days ago

Covington, KY 26-August-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.