2

对于我的项目,我使用两个库:

  1. FluentValidation (http://fluentvalidation.codeplex.com/) 用于视图模型验证
  2. MVC 扩展 (http://mvcextensions.codeplex.com/) 为我的视图模型流畅地配置元数据

这是我配置它们的方式(这是在容器构建器类中完成的):

    /* Model Metadata Registration */
    IEnumerable<IModelMetadataConfiguration> configurations = container.Resolve<IEnumerable<IModelMetadataConfiguration>>();

    IModelMetadataRegistry registry = new ModelMetadataRegistry();

    configurations.Each(configuration => registry.RegisterModelProperties(configuration.ModelType, configuration.Configurations));

    ModelMetadataProviders.Current = new ExtendedModelMetadataProvider(registry);

    /* Fluent Validation Configuration */
    FluentValidationModelValidatorProvider.Configure(x =>
    {
        x.ValidatorFactory = container.Resolve<IValidatorFactory>();
        x.AddImplicitRequiredValidator = false;
    })

现在,当我运行应用程序时,FluentValidationModelValidatorProvider 不会验证模型。而是使用默认机制。因此我不得不注释掉 FluentValidationModelValidatorProvider 配置并改用这种方法:

    IValidator validator = _validatorFactory.GetValidator(typeof(RegisterUserCommand));
    ValidationResult result = validator.Validate(command);

接着:

        if (!result.IsValid)
        {
            command.Password = String.Empty;
            command.ConfirmPassword = String.Empty;

            ModelState.Clear();

            ModelState.AddModelErrors(result.Errors);

            return View(command);
        }

但必须有一种方法让它们一起工作。有什么建议吗?

4

1 回答 1

0

我使用 FluentValidation,它工作正常。我在 App_Start 处调用了以下内容。

public static void Start()
{
    var factory = new DependencyResolverValidatorFactory();
    var provider = new FluentValidationModelValidatorProvider(factory);

    // add remote capabilities
    FluentValidationModelValidationFactory validationFactory = (metadata, context, rule, validator) => new RemoteFluentValidationPropertyValidator(metadata, context, rule, validator);
    provider.Add(typeof(RemoteValidator), validationFactory);

    ModelValidatorProviders.Providers.Add(provider);
    DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
}
于 2013-12-06T20:00:33.560 回答