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

Mat*_*LES 6 asp.net-core-2.1

TLDR;如何获得行为

[Required(ErrorMessage = "Le champ {0} est obligatoire")]
Run Code Online (Sandbox Code Playgroud)

虽然只是写作

[Required]
Run Code Online (Sandbox Code Playgroud)

据我了解,该文档没有提供一种隐式本地化一组给定 DataAnnotations 的方法。

我希望有注释的错误消息,例如RequiredStringLength可以覆盖而不触及其他人,例如Display并且不需要使用ErrorMessage属性明确指定翻译。

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

我尝试了以下方法:

这个GitHub 线程

在里面 Startup.cs

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

给了我以下错误

无法分配属性或索引器“DefaultModelBindingMessageProvider.AttemptedValueIsInvalidAccessor”——它是只读的

我找不到任何可以作为这个对象的 setter 的属性。


这个SO答案

Startup.cs services.AddSingleton();

并创建一个类,如跟随

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

    public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
    {
        /* override message */
    }
}
Run Code Online (Sandbox Code Playgroud)

但这仅捕获了DataType注释

And*_* S. 2

在.Net Core 2中,Accessor中的属性ModelBindingMessageProvider是只读的,但您仍然可以使用Set...Accessor()方法来设置它们。这里的代码与我正在使用的代码类似,感谢ASP.NET Core Model Binding Error Messages Localization的答案。

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