定制DataAnnotationsModelValidatorProvider服务器端验证 [英] Server side validation with custom DataAnnotationsModelValidatorProvider

查看:326
本文介绍了定制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.

推荐答案

我终于想通了这一点,这是一个pretty简单的答案。该ApiControllers只响应被用于常规控制器和客户端验证在System.Web.Http.Validation命名空间,而不是System.Web.Mvc命名空间提供者。

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.

我实现既实现无论是在ApiControllers客户端验证和服务器验证。

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

这篇关于定制DataAnnotationsModelValidatorProvider服务器端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆