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

C# Extension Methods Example

In this article i am going to explain about Extension Methods  with example. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive. ...

VBScript equivalent string functions in C#.Net

C# Method VBScript Description IndexOf() InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string - InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string ToLower() LCase Converts a specified string to lowercase SubString() Left Returns a specified number of characters from the left side of a string Length() Len Returns the number of characters in a string TrimStart() LTrim Removes spaces on the left side of a string TrimEnd() RTrim Removes spaces on the right side of a string Trim() Trim Removes spaces on both the left and the right side of a string SubString() M...