Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Created May 25, 2012 20:54
Show Gist options
  • Save tugberkugurlu/2790493 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/2790493 to your computer and use it in GitHub Desktop.
ValidateModelStateAttribute Action Filter
public class ValidateModelStateAttribute : ActionFilterAttribute {
public override void OnActionExecuting(HttpActionContext actionContext) {
var modelState = actionContext.ModelState;
if (!modelState.IsValid) {
var errors = modelState.Keys
.Where(key => modelState[key].Errors.Any())
.Select(key => new Dictionary<string, string> {
{ key, modelState[key].Errors.First().ErrorMessage }
});
//this way, conneg is done by the server
var response = actionContext.Request.CreateResponse<IEnumerable<Dictionary<string, string>>>(
HttpStatusCode.BadRequest, errors
);
actionContext.Response = response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment