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

Sort Dictionary Based On Value In Asp.Net And C#.Net | Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.

In this tutorial i am going to explain about how to sort dictionary object based on value in asp.net and C#.Net or convert unsorted dictionary to sorted dictionary object in C#.Net and VB.Net or Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.

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)     { ...

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;