Created
June 3, 2012 02:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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