定制DataAnnotationsModelValidatorProvider服务器端验证

我已经建立了自定义提供,以允许设置验证从数据存储,而不是静态code属性。伟大工程在我的.NET MVC 4项目的客户端验证,但我无法获取服务器端验证工作。

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:

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

在我的Global.asax.cs我有:

In my Global.asax.cs I have:



    protected void Application_Start()
    {
        ModelValidatorProviders.Providers.Clear();
        ModelValidatorProviders.Providers.Add(new CustomModelValidatorProvider());
    }

和在Web API方法,我有:

And in a Web API method I have:



    var validationResultList = new List();
    bool valid = Validator.TryValidateObject(myModelObject, new ValidationContext(myModelObject, null, null), validationResultList, true);

下面,有效的始终是真实的。即使Jquery的客户端验证显示错误。在服务器端,我的自定义提供不使用应用数据的注释。当我设置在GetValidators断点()时创建视图并正确显示客户端验证它的名字,但是当模型被绑定到控制器不会再次被调用。

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.

有我错过了一步?任何帮助是极大AP preciated!

Have I missed a step? Any help is greatly appreciated!

更新

自定义验证工作正常当对象被发布到一个控制器,但是当贴到ApiController不会被解雇。

The custom validator works correctly when the object is posted to a Controller, but does not get fired when posted to an ApiController.



 1 条回答