chobo2 chobo2 - 1 year ago 137
C# Question

Validation For WebApi?

I am using the 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.


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);
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.

Answer Source

Regarding your problem with [DataContract(IsRequired=true)], there are some posts on SO itself describing why it was needed (security concerns) and why it's not needed anymore (buggy). For reference: ASP.NET Web Api validation datacontract and datamember required

All you need to do to rely only on DataAnnotation attributes ist to remove InvalidModelValidatorProvider from the Web Api Config, like so:

config.Services.RemoveAll(typeof(ModelValidatorProvider), (provider) => provider is InvalidModelValidatorProvider);

Actually you are right, this line

return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

will send your validation errors back to the client. What is meant by the excerpt you cited is that you must write this line either in controller's action body or in a validation filter.

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download