Home
Do You Apply the ValidateModel Attribute to All Controllers?
  v1.0 Posted at 6/11/2014 5:46 AM by Tiago Araujo
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

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments: