Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created July 20, 2012 17:16
Show Gist options
  • Save benfoster/3151971 to your computer and use it in GitHub Desktop.
Save benfoster/3151971 to your computer and use it in GitHub Desktop.
Validating ModelState in WebApi
public class ValidateModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
var errors = from k in actionContext.ModelState.Keys
from e in actionContext.ModelState[k].Errors
select new ValidationError { ParameterName = k, ErrorMessage = e.ErrorMessage };
var response = actionContext.Request.CreateResponse<ValidationError[]>(HttpStatusCode.BadRequest, errors.ToArray());
throw new HttpResponseException(response);
}
base.OnActionExecuting(actionContext);
}
}
public class ValidationError
{
public string ParameterName { get; set; }
public string ErrorMessage { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment