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

Developer - Web
Source: Geocaching
Details: Proficient with ASP.NET, MVC, REST, WCF, Web API and scalable service oriented architectures. About Geocaching HQ....  More
16 days ago

Seattle, WA 98103 07-January-2017

C# Software Developer (Web Services & API)
Source: Indeed
Details: C#, ASP.NET, MVC or better required, Java/Node.js a plus. If you’re looking for a rewarding career with a dynamic and fast-growth healthcare software company,...  More
10 days ago

Seattle, WA 12-January-2017

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

Redmond, WA 30-November-2016

Sr. Web Developer (.Net/SharePoint)
Source: V3Main Technologies Inc.
Details: ASP.NET , VB.NET , C#, MVC, Entity Framework, Ajax, Bootstrap, JSON, jQuery, Knockout, HTML5, CSS3, IIS, SSL, TLS, SSH, TFS, FTP, XML, XLST, Classic ASP,...  More
6 days ago

Houston, TX 16-January-2017

.NET Developer
Source: TS Solutions
Details: ASP.NET MVC (4), C#, Azure, SQL Server. TokuSaku (TS) Solutions is looking for .NET developer with numerous bolt-on skill sets to help with our list of direct...  More
3 days ago

Seattle, WA 19-January-2017

.NET Web Application Developer
Source: NIC
Details: MVC. In-depth experience with C#, ASP.NET and MVC. Leading Web Services and E-Commerce company seeking two full-time .NET Web Application Developers to...  More
10 days ago

Frankfort, KY 13-January-2017

.NET Web Developer
Source: NIC
Details: MVC. Leading Web Services and E-Commerce company seeking a full-time .NET Web Application Developer to complement our growing team in Jackson, Mississippi....  More
11 days ago

Jackson, MS 11-January-2017

.NET Web Developer
Source: Springbox
Details: Experience with (.NET) MVC, MVP, MVVM architecture design and an understanding of design patterns, in particular OO/IoC/DI....  More
13 days ago

Austin, TX 78701 10-January-2017

Sr. Web Developer & Designer
Source: Indeed
Details: Expertise in most of the following –Web API (MS ASP.Net), MVC, WCF, HTML5, CSS, JavaScript, JSON, SOAP, REST, JQuery, .Net Framework, C#, Web Services....  More
2 days ago

Austin, TX 73301 20-January-2017

Web Developer
Source: Indeed
Details: Programming experience ASP.Net MVC, JavaScript and C# required. Securitas Security Services USA, Inc....  More
2 days ago

Westlake Village, CA 20-January-2017

.NET Web Developer
Source: Blue Earth Interactive
Details: Experience with popular web application frameworks, such as Kendo/Telerik MVC. About Blue Earth:....  More
13 days ago

Saint Paul, MN 55101 09-January-2017

Web Developer/Programmer
Source: Indeed
Details: Don't miss this great opportunity to join a leader in the equipment business at Messick’s in Elizabethtown. We are looking for a *C#* *.NET Web Engineer* to  More
4 days ago

Elizabethtown, PA 18-January-2017

Windows C# .NET MVC Web Portal Developer in Ft. Lauderdale,FL
Source: Indeed
Details: Have Experience in MVC 4.0 and 5.0 and capable of working in projects with MVC. Windows C# .NET MVC Web Portal Developer - Contract....  More
5 days ago

Fort Lauderdale, FL 18-January-2017

.Net Full Stack Developer
Source: Sonsoft Inc
Details: At least 4 years of product development experience in Dot Net technologies (C#, ASP.Net, MVC, MVVM, WCF, SQL Server)....  More
5 days ago

Redmond, WA 18-January-2017

Entry Level Developer
Source: Fairfax Data Systems
Details: Must possess a strong desire to work with different programming languages like .Net (C#, VB.Net/asp.net mvc), Java/J2EE, etc., and learn new technologies like...  More
30+ days ago

New Milford, CT 06776 13-December-2016

.NET Web Developer (Denver, CO) (Long-term Contract)
Source: Chipotle Mexican Grill
Details: ASP.Net MVC and Razor; .NET Web Developer (Denver, CO) (Long-term Contract) (17000744) Description....  More
17 days ago

Denver, CO 05-January-2017

ASP.NET / C# Software Developer (Web Services & API)
Source: Indeed
Details: C#, ASP.NET, MVC or better required, Java/Node.js a plus. The Software Developer is an experienced engineer that uses C#, ASP.NET, MVC to build web services,...  More
7 days ago

Tacoma, WA 16-January-2017

Web Developer
Source: Indeed
Details: Programming experience ASP.Net MVC, JavaScript and C# required. Securitas Secuirty Services USA, Inc....  More
9 days ago

Westlake Village, CA 13-January-2017

Wellness Programs Web Developer (Consultant)
Source: Indeed
Details: Knowledge and experience developing custom applications using MVC is essential. Develop web applications using VISUAL STUDIO.NET, ASP.NET, MVC, ADO.NET, XML,...  More
9 days ago

Brooklyn, NY 11201 13-January-2017

Full Stack .NET Developer (C#/JavaScript/SQL/Web Services)
Source: CareWorks Tech
Details: This position will: Develop and support web, middleware and database applications for internal and external deployment. Develop, implement and test project...  More
10 days ago

Columbus, OH 12-January-2017

C# ASP.Net Web Developer
Source: Indeed
Details: Experience with various web technologies, such as HTML, CSS, AJAX, JQuery, JavaScript, AngularJS, Bootstrap, XML, ASP.NET, MVC, WebForms, Web Services, IIS....  More
10 days ago

Irvine, CA 12-January-2017

.Net Full Stack Developer
Source: Sonsoft Inc
Details: At least 4 years of product development experience in Dot Net technologies (C#, ASP.Net, MVC, MVVM, WCF, SQL Server)....  More
5 days ago

Bellevue, WA 18-January-2017

Front End Web Developer
Source: Indeed
Details: *Title: * Senior Web Developer *Reports to: * Digital Channel Manager *Status: * Full-time, exempt *Location: * Boston It takes talent to be the world's  More
12 days ago

Boston, MA 10-January-2017

C# .NET Web Developer - Green Bay, WI or Indianapolis, IN
Source: UnitedHealth Group
Details: Candidates must have strengths in C#, a clear understanding of ASP.NET MVC. Welcome to one of the toughest and most fulfilling ways to help....  More
26 days ago

Indianapolis, IN 46218 28-December-2016

Jr .Net Developer
Source: Indeed
Details: Familiar with Web-API and REST in the ASP.NET MVC world. Professional job experience with C# and ASP.NET MVC (not just ASP.NET web forms). Full time/Long Term*....  More
24 days ago

Redmond, WA 29-December-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.