Search code examples
asp.net-web-apiodata

Enforcing data contracts on posts in odata


What is the best way to enforce required fields, field lengths, and other validation on put and post requests for WebAPI based OData requests?

I have had some success with [Required] attributes, but in the past we have used [DataContract] and [DataMember(IsRequired=true), on the entity classes, but that doesn't seem to cause the ModelState.IsValid to return false when a field with the [DataMember(IsRequired=true) is left off the json posted to the request.


Solution

  • It appears that the proper solution is to add both the [DataMember(IsRequired=true)] and the [Required] attributes to each data item you wish to enforce as required.