Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tugberkugurlu/2862518 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/2862518 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