ASP.Net Web Api Model Validation Using Validation Filters

By
Advertisement
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..

1 comment:

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

    ReplyDelete

Online Casino