Server side validation with custom DataAnnotationsModelValidatorProvider

偶尔善良 提交于 2019-11-29 21:16:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/11785311/server-side-validation-with-custom-dataannotationsmodelvalidatorprovider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!