I am using the asp.net web api and I don't know if I am doing something wrong but I find it for some reason alot harder to use DataAnnotations for validation with WebApi vs MVC.
For instance if I want to use the Required Validator on a non string I have to use a DataContract with IsRequired what I find adds to the clutter.
I also find that if the data annotation fails to validate that I really don't get an error back(RestSharp thinks all is well).
I am wondering do people use anything other than DataAnnotations with the WebApi? I know in MVC there was that Fluent Validation for .net but not sure if that works with WebApi.
Edit
I am bit confused base on the link in the comments.
In the first part they have this
if (ModelState.IsValid)
{
// Do something with the product (not shown).
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
I thought Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); will send all the model state errors back.
But then it goes
Handling Validation Errors
Web API does not automatically return an error to the client when validation fails. It is up to the controller action to check the model state and respond appropriately.
I am confused about the above line as like I said I thought CreateErrorResponse was handling that.
Request.CreateErrorResponseinside the controller. The second is to apply filter attribute to controller or use global filter. And inside the filter is similaractionContext.Request.CreateErrorResponse. "Web API does not automatically return an error to the client" means that in default configuration (i.e. without filter or model state check inside controller) you won't obtain validation error information. - Vladimir