it:ad:asp.net:webapi:howto:perform_validation

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
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());
  • /home/skysigal/public_html/data/pages/it/ad/asp.net/webapi/howto/perform_validation.txt
  • Last modified: 2023/11/04 02:15
  • by 127.0.0.1