Skip to content

Instantly share code, notes, and snippets.

@bradwilson
Created June 3, 2012 02:58
Show Gist options
  • Save bradwilson/2861378 to your computer and use it in GitHub Desktop.
Save bradwilson/2861378 to your computer and use it in GitHub Desktop.
A filter for ASP.NET Web API to return 400 upon invalid model binding
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
[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
);
else
base.OnActionExecuting(actionContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment