Tuesday, 28 June 2016

Web API : Create an attribute to validate the model state.

In the web api often we need to validate the model properties for check that the input data is validate or not. This ValidateModelAttribute helps you to validate all the models in all the post actions in one place. You no need to apply check on modelstate in every action method. Check this out.

Step 1 :-Create new class ValidateModelAttribute.cs and inherit it from ActionFilterAttribute. Now paste the following code in that class.

 public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            string errorsString = string.Empty;
            if (actionContext.ModelState.IsValid == false)
            {
                var errors = new List<string>();
                foreach (var state in actionContext.ModelState)
                {
                    foreach (var error in state.Value.Errors)
                    {
                        if (!string.IsNullOrEmpty(error.ErrorMessage))
                            errors.Add(error.ErrorMessage);
                    }
                }

                if (errors.Any())
                {
                    errorsString = string.Join(",", errors);
                }

                actionContext.Response = actionContext.Request.CreateResponse(
                    HttpStatusCode.BadRequest, errorsString);
            }
        }
    }

Step 2: Usage- You can use this class as an attribute on the api method where you want the check model validations:

        [HttpPost]
        [Route("SaveCustomer")]
        [ValidateModel]
        public async Task<IHttpActionResult> SaveCustomer(CustomerInfo info)
        {
            return Ok();
        }

No comments:

Post a Comment