TLDR;如何获取行为
[Required(ErrorMessage = "Le champ {0} est obligatoire")]
虽然只写
[Required]
据我了解,文档没有提供隐式本地化一组给定 DataAnnotations 的方法。
我希望有诸如注释的错误消息,Required
并且StringLength
可以在不触及其他注释的情况下被覆盖,Display
并且不需要使用ErrorMessage
属性显式指定翻译。
注意:我只需要将消息翻译成法语,因此不需要将解决方案绑定到请求的语言。
我尝试了以下方法:
从这个GitHub 线程
在里面Startup.cs
services.AddMvc(options => options.ModelBindingMessageProvider.AttemptedValueIsInvalidAccessor =
(value, name) => $"Hmm, '{value}' is not a valid value for '{name}'."));
给我以下错误
无法将属性或索引器“DefaultModelBindingMessageProvider.AttemptedValueIsInvalidAccessor”分配给 - 它是只读的
而且我找不到任何可以用作该对象的设置器的属性。
从这个答案
在Startup.cs
services.AddSingleton();
并创建一个像follow这样的类
public class LocalizedValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
{
private readonly ValidationAttributeAdapterProvider _originalProvider = new ValidationAttributeAdapterProvider();
public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
{
/* override message */
}
}
但这仅捕获了DataType
注释