Created
July 20, 2012 17:16
-
-
Save benfoster/3151971 to your computer and use it in GitHub Desktop.
Validating ModelState in WebApi
This file contains hidden or 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
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