Created
May 25, 2012 20:54
-
-
Save tugberkugurlu/2790493 to your computer and use it in GitHub Desktop.
ValidateModelStateAttribute Action Filter
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) { | |
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