Do You Apply the ValidateModel Attribute to All Controllers?

Last updated by Brook Jeynes [SSW] 6 months ago.See history

This rule has been archived
Archived Reason: Requested by Matt G under RE: Update [SSW] Rules to Better WebAPI

Web API does not automatically return an error to the client when validation fails. It is up to the controller action to check the model state and respond appropriately.

You can also create an action filter to check the model state before the controller action is invoked.

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 MyApi.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);
 }
 }
 }
 }

Figure: If model validation fails, this filter returns an HTTP response that contains the validation errors. In that case, the controller action is not invoked

public class ProductsController : ApiController
 {
 [ValidateModel]
 public HttpResponseMessage Post(Product product)
 {
 // ...
 }
 }

Figure: Bad Example - Set the filter as an attribute on individual controllers or controller actions

public static class WebApiConfig

    {

        public static void Register(HttpConfiguration config)

        {

            config.Filters.Add(new ValidateModelAttribute());



            // ...

        }

}

Figure: Good Example - Add an instance of the filter to the HttpConfiguration.Filterscollection to apply this filter to all Web API controllers

We open source. Powered by GitHub