Server side validation with custom DataAnnotationsModelValidatorProvider

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.


I finally figured this out, it's a pretty simple answer. The ApiControllers only respond to the providers in the System.Web.Http.Validation namespace, not the System.Web.Mvc namespace that is used for regular Controllers and the client side validation.

I implemented both to achieve both the client side validation and server validation in the ApiControllers.

链接地址: http://www.djcxy.com/p/56648.html

上一篇: ASP MVC验证时间

下一篇: 使用自定义DataAnnotationsModelValidatorProvider进行服务器端验证