idatorProvider和IModelValidator实现

idatorProvider和IModelValidator实现

本文介绍了IModelValidatorProvider和IModelValidator实现的问题.产生的错误未得到正确处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在ASP.NET Core项目中使用 IModelValidatorProvider IModelValidator 接口分别进行模型验证.

I try to use IModelValidatorProvider and IModelValidator interfaces in my ASP.NET Core project for respective model validation.

不幸的是,它无法按预期工作.即我的 ModelValidator 类(实现 IModelValidator )仅返回一个错误.结果,我看到 ModelState 包含一个带有预期文本的错误.没事. ModelState.ErrorsCount = 1 .但是问题是在 ModelState.Values 中提供了新元素.它具有键 Code.Code 而不是 Code ,其中 Code 是模型属性之一的名称.这就是为什么页面视图上 Code 属性的验证字段中未显示所需文本的原因.如果在控制器中使用 ModelState.AddModelError 方法,情况将有所不同.

Unfortunately it does not work as expected.Namely my ModelValidator class (implements IModelValidator) returns only one error. As a result I see that ModelState contains one error with the expected text. It is fine.ModelState.ErrorsCount = 1.But the problem is new element is presented in ModelState.Values.It has a key Code.Code instead of Code where Code is name of one of the model property. That is why the required text is not shown in validation field for Code property on page view.The situation is different if I use ModelState.AddModelError method in the controller.

ModelState.AddModelError("Code", "something went wrong...");

ModelState.Values 不包含键为 Code.Code 的其他元素.它包含具有键 Code ( ValidationState = Invalid )的元素,并且正确显示了错误消息.

ModelState.Values does not contain additional element with key Code.Code. It contains element with key Code (ValidationState=Invalid) and a error message is shown correctly.

我想我在模型验证器上做错了什么.但是我被困住了,无法找到确切的问题.感谢您的任何建议.

I guess I am doing something wrong with model validators. But I am stuck and can't find the exact issue. Would be thankful for any advice.

请在下面找到我的验证器的源代码

Please find below the source code of my validators

public class CustomModelValidatorProvider : IModelValidatorProvider
{

    public CustomModelValidatorProvider()
    {
    }

    public void CreateValidators(ModelValidatorProviderContext context)
    {
        if (context.Results.Any(v => v.Validator.GetType() == typeof(MyCustomModelValidator)) == true)
        {
            return;
        }

        if (context.ModelMetadata.ContainerType == typeof(DealRegistrationViewModel))
        {
            context.Results.Add(new ValidatorItem
            {
                Validator = new MyCustomModelValidator(),
                IsReusable = true
            });
        }
    }
}

public class MyCustomModelValidator : IModelValidator
{
    public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
    {
        var model = context.Container as DealRegistrationViewModel;

        if (context.ModelMetadata.ModelType == typeof(string)
                && context.ModelMetadata.Name == nameof(model.Code))
        {
            if (string.IsNullOrEmpty(model.Code) == true)
            {
                return new List<ModelValidationResult>
                {
                    new ModelValidationResult(context.ModelMetadata.PropertyName, "Empty Code value is not accepted")
                };
            }
        }

        return Enumerable.Empty<ModelValidationResult>();
    }
}

像这样在 startup.cs 中激活验证器

services.AddMvc(options =>
{
    options.ModelValidatorProviders.Add(new CustomModelValidatorProvider());
});

在使用 ModelState.AddModelError 的情况下(请正常使用),请在下面找到带有 ModelState.Values 内容的屏幕快照

Please find below with screenshot with ModelState.Values content in case of ModelState.AddModelError usage (works fine)

在使用模型验证器的情况下,请在下面找到带有 ModelState.Values 内容的屏幕截图(无法正常工作)

Please find below with screenshot with ModelState.Values content in case of Model validators usage (it does not work fine)

推荐答案

您只需要在您的 MyCustomModelValidator 中更改代码,如下所示:

You just need to change your code in your MyCustomModelValidatorlike below:

if (string.IsNullOrEmpty(model.Code) == true)
            {
                return new List<ModelValidationResult>
                {
                   new ModelValidationResult("", "Empty Code value is not accepted")
                };

            }

测试结果:

这篇关于IModelValidatorProvider和IModelValidator实现的问题.产生的错误未得到正确处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 06:51