Saturday, November 22, 2014

Web API - Bad Request when Model State is Invalid

When you using Web API, would you like to always return a 400 (bad request) response whenever the model state is invalid? It is easy, just add the following filter attribute to your global list:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, 
    AllowMultiple = false, 
    Inherited = true)]
public class InvalidModelStateFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, 
                actionContext.ModelState);
        }
    }
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics