如何从“自定义属性”翻译“ErrorMessage”

Ric*_*rdo 3 c# asp.net-core-mvc asp.net-core asp.net-core-2.1

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

\n\n

使用正确本地化了Required 的属性的示例。

\n\n
[Required(ErrorMessage = "CPF Requerido")]\n[CPF(ErrorMessage = "CPF Inv\xc3\xa1lido")]\npublic string CPF { get; set; }\n
Run Code Online (Sandbox Code Playgroud)\n\n

设置 Startup.cs 文件中的位置

\n\n
services\n    .AddMvc()\n    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)\n    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)\n    .AddDataAnnotationsLocalization(options =>\n    {\n        options.DataAnnotationLocalizerProvider = (type, factory) =>\n        {\n             return factory.Create(typeof(SharedResource));\n        };\n    });\n
Run Code Online (Sandbox Code Playgroud)\n\n

自定义验证类:

\n\n
public class CPFAttribute : ValidationAttribute\n{\n    protected override ValidationResult IsValid(object value, ValidationContext context)\n    {\n        //Omitted for not being part of the context\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

版本:

\n\n

微软.AspNetCore.App (2.1.1)

\n\n

微软.NETCore.App (2.1)

\n
\n

Yac*_*ran 5

实现属性适配器:

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());
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

并在 Startup.cs 中写入:

    services.AddSingleton<IValidationAttributeAdapterProvider, CPFAttributeAdapterProvider>();
Run Code Online (Sandbox Code Playgroud)