Today, I will explain how to validate Web API using model validation or data annotation on the client side. We can perform model validation in MVC in an easy way. In API, when sending the request by the client or user to web API, then before doing the next process, it checks the empty validation and handles the validation error using data annotation in WEB API.
So now, let us see step by step.
Step 1
First, we will add a Web API project. For that, open Visual Studio -> File -> Select ASP.NET Web Application -> Select API and click OK.
Step 2
After that, we will add a database using model first approach. So, for this, go to the model folder and then right click -> Select Add option -> New Item -> Data (Left Panel) -> Choose ADO .NET Entity Data Model - > Click Ok -> Select EF Designer from database -> Next -> Select New Connection -> and give the server name and user id and password of your SQL Server

After that click on test connection -> Ok ->Ok -> Select Next -> Expand the tables and check our table -> after that Click Finish button
Step 3
After finishing the second step now we will go to model folder and select our class. Here I am using RegisterUser(Demo) class.
- namespace WebApiValidation.Models
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- public partial class RegisterUser
- {
- public int UserID { get; set; }
- [Required(ErrorMessage = "Please enter User Name")]
- public string UserName { get; set; }
- [Required(ErrorMessage = "Please enter Password")]
- public string Password { get; set; }
- [Required(ErrorMessage = "Please enter Email Id")]
- public string EmailID { get; set; }
- public Nullable<System.DateTime> CreateOn { get; set; }
- }
- }
After that we will go to our solution and add a Filter folder and right click filter folder and add a class

After adding ValidateModelRegister Class now we are going to inherit from ActionFilterAttribute class inside that we are going to write our custom logic like as shown below
- 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 WebApiValidation.Filter
- {
- public class ValidateModelRegister : ActionFilterAttribute
- {
- }
- }
After inheriting from ActionFilterAttribute now let us implement OnActionExecuting method of it. In this method we are going check if the Model which is posted is valid or not; if not then we are going to CreateErrorResponse as shown below.
- 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 WebApiValidation.Filter
- {
- public class ValidateModelRegister : ActionFilterAttribute
- {
- public override void OnActionExecuting(HttpActionContext actionContext)
- {
- if (actionContext.ModelState.IsValid == false)
- {
- actionContext.Response = actionContext.Request.CreateErrorResponse(
- HttpStatusCode.BadRequest, actionContext.ModelState);
- }
- }
- }
- }
Now we will add a API controller so right click controller folder -> add ->Controller ->Select API Controller
- [RoutePrefix("api/UserReg")]
- public class RegisterAPIController : ApiController
- {
- }
After that we will add an action method for posting the data. Now that we have implemented OnActionExecuting method let’s apply it on our post method.
- [RoutePrefix("api/UserReg")]
- public class RegisterAPIController : ApiController
- {
- [HttpPost]
- [Route("Register")]
- [ValidateModelRegister]
- public string RegisterUser(RegisterUser data)
- {
- MKDBEntities objEntity = new MKDBEntities();
- data.CreateOn = System.DateTime.Now;
- objEntity.RegisterUsers.Add(data);
- int i= objEntity.SaveChanges();
- if(i > 0)
- {
- return "Successfully inserted ";
- }
- else
- {
- return "Insertion faild";
- }
- }
- }





Join the conversation! Your thoughts help the community grow.