隐式本地化法语中的“Required”注释

Localize `Required` annotation in French implicitly

TLDR; 如何获得

的行为
[Required(ErrorMessage = "Le champ {0} est obligatoire")]

只写

[Required]

据我了解,documentation 不提供隐式本地化一组给定的 DataAnnotations 的方法。

我希望 RequiredStringLength 等注释的错误消息可以覆盖,而无需触及 Display 等其他注释,也无需明确指定使用 ErrorMessage 属性进行翻译。

注意:我只需要将消息翻译成法语,因此无需将解决方案绑定到请求的语言。

我尝试了以下方法:

来自 this GitHub 线程

Startup.cs

services.AddMvc(options => options.ModelBindingMessageProvider.AttemptedValueIsInvalidAccessor =
    (value, name) => $"Hmm, '{value}' is not a valid value for '{name}'."));

给我以下错误

Property or indexer 'DefaultModelBindingMessageProvider.AttemptedValueIsInvalidAccessor' cannot be assigned to -- it is read only

而且我找不到任何 属性 可以用作此对象的 setter。


来自this 所以回答

Startup.cs services.AddSingleton();

并创建一个 class 关注

public class LocalizedValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
{
    private readonly ValidationAttributeAdapterProvider _originalProvider = new ValidationAttributeAdapterProvider();

    public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
    {
        /* override message */
    }
}

但这只捕获了 DataType 注释

在 .Net Core 2 中,ModelBindingMessageProvider 中的 Accessor 属性是只读的,但您仍然可以使用 Set...Accessor() 方法设置它们。这是与我正在使用的代码类似的代码,感谢对 .

的回答
public static class ModelBindingConfig
{
    public static void Localize(MvcOptions opts)
    {
        opts.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor(
            x => string.Format("A value for the '{0}' property was not provided.", x)
        );

        opts.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(
            () => "A value is required."
        );
    }
}


// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddMvc(
        opts =>
        {
            ModelBindingConfig.Localize(opts);
        })
        .AddViewLocalization()
        .AddDataAnnotationsLocalization();
}