Skip to main content

ASP.Net Web Api Model Validation Using Validation Filters

In this tutorial i am going to explain about how to validate Model properties in asp.net mvc web api. It can be achieved by using the attributes from the System.ComponentModel.DataAnnotations namespace to set validation rules for properties on your model.

In my previous article i have explained about Build Products Comparision Table/Grid In ASP.Net , Store Custom Objects In Configuration File , Create Simple Mathmatical Captcha In ASP.Net , Visual Studio Keyboard Shortcuts , How To get data from WEB API , How To Create Your First WEB API Project and many articles in C#.Net,VB.Net,Grid View,Javascript,jQuery,SQL Server and many other topics.

When the client sends the request to Web API It is necessary to validate the properties of the Model before starting any action to do. In the web API for this purpose we can use annotations from the namespace System.ComponentModel.DataAnnotations. To explain about how to apply the validation for the model properties we first need to create the asp.net WEB API project first. For this refer my previous article How To Create Your First WEB API Project or else follow the simple steps mentioned below.

Open the visual studio and go to file menu then select New Project. Then from the installed project templates select ASP.Net Web Application and name your application and select the appropriate folder as shown in the figure.
Step 1 of ASP.Net Web Api Model Validation Using Validation Filters

Now do right click on the model folder and then select Add then Class. Name your class as Employee.cs and then add the following code in your Employee.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//Include this namespace if it is not already there
using System.ComponentModel.DataAnnotations;

namespace WebAPIModelValidation.Models
{
    public class Employee
    {
        [RegularExpression("^[0-9]*$")]
        public int EmployeeId { get; set; }

        [StringLength(10), Required]
        public string EmployeeName { get; set; }

        public string FatherName { get; set; }
       
        [Range(0, 99)]
        public Int16 YearsOfExperience { get; set; }

        [RegularExpression("^[0-9]*$"), Required, StringLength(10)]
        public string MobileNo { get; set; }

        [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$")]
        public string EmailId { get; set; } 
    }
}

All the validation attributes are in the System.ComponentModel.DataAnnotations namespace. Here i have used RegularExpression for validating EmployeeId,MobileNo and EmailId. The Required attribute ensures that the property is mandatory. Now create a new folder called Filter if it is not already there and add a class file named ValidateModelAttribute.cs and then add the below code.

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;

namespace WebAPIModelValidation.Filters
{
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }
}

Now we can validate the model using two ways.One is by checking ModelState.IsValid boolean property. It returns true if model is valid else return false. And the another way is [ValidateModel] http attribute to individual controllers or controller actions. Below is the sample code for the two methods.
Method - 1:


// POST api/Employee/Post
// Using ModelState.IsValid
public IHttpActionResult Post(Employee employee)
{
    if (ModelState.IsValid)
    {
        return Ok();
    }
    else
        return BadRequest(ModelState); 
}

Method - 2:


// POST api/Employee/PostV2
// Using ValidateModel Attribute
[ValidateModel]
public IHttpActionResult PostV2(Employee employee)
{
    return Ok();
}

Now if you run your api by passing some valid values to model attributes then it will return the http response as Ok(Response Code 200). Below is the sample output.

Output 1 of ASP.Net Web Api Model Validation Using Validation Filters

But if you pass the invalid values to model attributes then it will return the error as shown below.
Output 2 of ASP.Net Web Api Model Validation Using Validation Filters

SourceCode:

Source Code of ASP.Net Web Api Model Validation Using Validation Filters
If you like this article then share with your friends and comment your valuable feedback.. Happy coding..

Comments

  1. I am looking for global validation to avoid any script tag for all models.

    ReplyDelete

Post a Comment

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     {         sb.Append( "Minus " );         inputNo = -inputNo;     }     string [] words0 = { "" , "One " ,

C# code to send mail using smtp from gmail,yahoo mail and live mail

Introduction: In my previous article I have explained about   How to bind/Unbind events in jQuery . In this article I am going to explain about how to send mail from ASP.Net using gmail,yahoomail and live mail credentials. Explanation: First Include the below namespaces in your code behind file. using System; using System.Net; using System.Net.Mail;

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw