IT:AD:ASP.NET:WebAPI:HowTo:Validation
Summary
- Most POC requests are scalar.
- But once you get going, you should be using a RequestObject (some class with properties enough to describe the request).
- As it is a class/object, once can use standard DataAnnotation (like Required, min/max length, etc.)
- You can validate all of them using a single solution: a ValidationActionFilter
Process
public class ValidationActionFilter: ActionFilterAttribute {
var modelState = context.ModelState;
if (modelState.IsValid) {return;}
dynamic errors = new JsonObject();
foreach(var key = in modelState.Keys){
var state = modelState[key];
if (state.Errors.Any()) {
error[key] = state.Errors.First.ErrorMessage;
}
context.Response =
new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest);
}
}
Have to register it globally:
config.Filters.Add (new ValidationActionFilter());