Question

I have a view model that implements IValidatableObject and also has several validation attributes. When I attempt to call an action on my ApiController, only the attribute validation is performed. Does ASP.NET Web API not support IValidatableObject? What's the alternative for complex validation that cannot be represented by a single attribute?

Edit: Somewhere along the line, I must have fudged something up. The validation mysteriously started working as expected. Looks like IValidatableObject is definitely supported by default.

Était-ce utile?

La solution

Not yet tried IValidatableObject on webapi, but it should be supported according to the documentation the Validation provider for DataAnnotations (DataAnnotationsModelValidatorProvider) provide also IValidatableObject validation. See here: http://msdn.microsoft.com/en-us/library/system.web.http.validation.providers(v=vs.108)

Anyway, you can use also Object level ValidationAttribute that you can use to decorated a class...It is not so easy as IValidatableObject, but should work.

Autres conseils

With Web API 2.1 (Microsoft.AspNet.WebApi nuget 5.1.x), I experienced IValidatableObject's Validate method not being called if any of the validation attributes are invalid. Hence, all validation attributes that have been applied to your class's properties must first pass as valid before that class's Validate method will be called.

If, for example, you have a property with the RequiredAttribute and you do not put a value in that field, your implementation of IValidatableObject's Validate method will not be called. Although not technically a bug, I expected the Validate method to be called every time I validate.

As of now, IValidatableObject is supported.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top