如何从 "Custom Attribute" 翻译 "ErrorMessage"

How to translate the "ErrorMessage" from a "Custom Attribute"

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

正确本地化 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));
        };
    });

自定义验证class:

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

Versions:

Microsoft.AspNetCore.App (2.1.1)

Microsoft.NETCore.App (2.1)

实施属性适配器:

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());
        }
    }

并实现属性适配器提供程序:

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>();