I have setup a custom provider to allow setting validation attributes from a data store instead of in static code. Works great with the client side validation in my .NET MVC 4 project, but I am unable to get the server side validation to work.
CustomModelValidatorProvider .cs:
public class CustomModelValidatorProvider : DataAnnotationsModelValidatorProvider { protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes) { // set attributes from datastore here return base.GetValidators(metadata, context, attributes); } }
In my Global.asax.cs I have:
protected void Application_Start() { ModelValidatorProviders.Providers.Clear(); ModelValidatorProviders.Providers.Add(new CustomModelValidatorProvider()); }
And in a Web API method I have:
var validationResultList = new List(); bool valid = Validator.TryValidateObject(myModelObject, new ValidationContext(myModelObject, null, null), validationResultList, true);
Here, valid is always true. Even when the Jquery client side validation displays an error. On the server side my custom provider is not being used to apply the data annotations. When I set a breakpoint in GetValidators() it's called when the View is created and correctly displays the client side validators, but does not get called again when the model is bound to the controller.
Have I missed a step? Any help is greatly appreciated!
UPDATE
The custom validator works correctly when the object is posted to a Controller, but does not get fired when posted to an ApiController.