Skip to content

Instantly share code, notes, and snippets.

@jayhjkwon
Created January 21, 2013 02:43
Show Gist options
  • Save jayhjkwon/4583288 to your computer and use it in GitHub Desktop.
Save jayhjkwon/4583288 to your computer and use it in GitHub Desktop.
Model validations in ASP.NET WebAPI
public class FilterConfig
{
public static void RegisterConfig(HttpConfiguration config)
{
// register global model validation filter
config.Services.RemoveAll(typeof(System.Web.Http.Validation.ModelValidatorProvider), v => v is System.Web.Http.Validation.Providers.InvalidModelValidatorProvider);
config.Filters.Add(new ValidationActionFilter());
}
}
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment