Created
January 21, 2013 02:43
-
-
Save jayhjkwon/4583288 to your computer and use it in GitHub Desktop.
Model validations in ASP.NET 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 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()); | |
} | |
} |
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 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