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";
- }
-
-
- }
- }
Step 4
Now we have completed the API part so now we are going to add an MVC controller for consuming API or posting in API and creating an action method and add view.
- public class MVCController : Controller
- {
-
- public ActionResult Register()
- {
- return View();
- }
- }
After that we will design our view page
- <h2>Registration Form</h2>
- <div>
- <form>
-
- <table>
- <tr>
- <td>User Name : </td>
- <td>
- <input type="text" id="txtUserName" class="form-control" />
-
- </td>
- </tr>
- <tr>
- <td>Password : </td>
- <td>
- <input type="password" id="txtPassword" class="form-control" />
- </td>
- </tr>
- <tr>
- <td>Email ID : </td>
- <td>
- <input type="email" id="txtEmail" class="form-control" />
-
- </td>
- </tr>
-
-
- <tr>
- <td></td>
- <td>
- <input type="button" value="Register" id="btnRegister" class="btn btn-primary" />
- </td>
- </tr>
- </table>
- </form>
- <div id="DivMessage">
-
- </div>
- </div>
Now we will write Ajax method for posting user registration details.
- <script src="~/Scripts/jquery-1.10.2.js"></script>
- <script type="text/javascript">
-
- $(document).ready(function () {
-
- $("#btnRegister").click(function () {
- $("#DivMessage").empty();
- var data = {
- UserName: $("#txtUserName").val(),
- Password: $("#txtPassword").val(),
- EmailID: $("#txtEmail").val()
- }
-
- $.ajax({
- url: "/api/UserReg/Register",
- type:"POST",
- data: data,
- contenttype: "application/json;utf-8",
- datatype:"json"
- }).done(function (resp) {
- $("#DivMessage").append('<table class="table"><tr><td style="color:green" width="50px">' + resp + '</td></tr>');
- }).error(function (err) {
-
- var validationErrors = $.parseJSON(err.responseText);
- $.each(validationErrors.ModelState, function (i, valText) {
-
- $("#DivMessage").append('<table class="table"><tr><td style="color:red" width="50px">' + valText + '</td></tr>');
-
- });
- });
-
- });
- });
-
- </script>
How does it work?
Here when user submits blank details then the request goes to Action method of API controller. Before the method is executed the ActionFilter on that method gets executed as ActionFilter and checks if model is valid or not. If it isn't valid then it will give error response of status code 400 and a message. In Ajax we used two methods -- done and error. When we send blank user details to the field the Ajax Post method gives an invalid message because it does not have any data, then it sends 400 bad responses.
$.parseJSON(err.responseText);
After getting an error we are going to iterate on the object and append a table for displaying the error message and we will append this table with a DIV tag.
- $.each(validationErrors.ModelState, function (i, valText) {
- $("#DivMessage").append('<table class="table"><tr><td style="color:red" width="50px">' + valText + '</td></tr>');
- });
Now see the output,
If it is valid then it will give success message
I hope this article was helpful for you.