如何从“自定义属性”转换“ ErrorMessage”

时间:2019-04-06 20:44:41

标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.1

我创建了一个自定义验证属性,该属性仅验证 CPF 属性是否为有效的CPF,但是当我本地化时,我注意到了该应用程序与框架正确定位消息的数据属性Required不同,我的自定义属性没有被框架本地化,

使用属性正确定位“必填”的示例。

[Required(ErrorMessage = "CPF Requerido")]
[CPF(ErrorMessage = "CPF Inválido")]
public string CPF { get; set; }

设置Startup.cs文件中的位置

services
    .AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization(options =>
    {
        options.DataAnnotationLocalizerProvider = (type, factory) =>
        {
             return factory.Create(typeof(SharedResource));
        };
    });

自定义验证类:

public class CPFAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        //Omitted for not being part of the context
    }
}
  

版本:

     

Microsoft.AspNetCore.App(2.1.1)

     

Microsoft.NETCore.App(2.1)

1 个答案:

答案 0 :(得分:0)

安装Ataptute适配器:

public class CPFAttributeAdapter : AttributeAdapterBase<CPFAttribute>
{
        public CPFAttributeAdapter(CPFAttributeattribute, IStringLocalizer stringLocalizer) : base(attribute, stringLocalizer) { }

    public override void AddValidation(ClientModelValidationContext context) { }
        public override string GetErrorMessage(ModelValidationContextBase validationContext)
        {
            return GetErrorMessage(validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName());
        }
    }

并实现Attripute适配器提供程序:

public class CPFAttributeAdapterProvider : IValidationAttributeAdapterProvider
{
    private readonly IValidationAttributeAdapterProvider _baseProvider = new ValidationAttributeAdapterProvider();

    public IAttributeAdapter GetAttributeAdapter(CPFAttribute attribute, IStringLocalizer stringLocalizer)
    {
        if (attribute is CPFAttribute)
            return new CPFAttributeAdapter(attribute as CPFAttribute, stringLocalizer);
        else
            return _baseProvider.GetAttributeAdapter(attribute, stringLocalizer);
    }

    public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
    {
        if (attribute is CPFAttribute) return
                new CPFAttributeAdapter(attribute as CPFAttribute,
        stringLocalizer);
        else return _baseProvider.GetAttributeAdapter(attribute, stringLocalizer);
    }
}

并将其写在Startup.cs中:

    services.AddSingleton<IValidationAttributeAdapterProvider, CPFAttributeAdapterProvider>();