如何在ASP.NET Core中本地化验证属性的标准错误消息 [英] How to localize standard error messages of validation attributes in ASP.NET Core
问题描述
如何在ASP.NET Core(v2.2)中本地化验证属性的标准错误消息?例如, [Required] 属性具有以下错误消息:" xxx字段为必填字段.". [EmailAddress] 具有" xxx字段不是有效的电子邮件地址."; [比较] 具有"'xxx'和'yyy'不匹配.",依此类推.在我们的项目中,我们不使用英语,我想找到一种方法来翻译标准错误消息,而又不直接将它们写在每个数据模型类的每个属性中
How to localize standard error messages of validation attributes in ASP.NET Core (v2.2)? For Example, [Required] attribute has this error message "The xxx field is required."; [EmailAddress] has "The xxx field is not a valid e-mail address."; [Compare] has "'xxx' and 'yyy' do not match." and so on. In our project we use not English language and I want to find a way how to translate standard error messages without writing them directly in every attribute of every data-model class
推荐答案
This is spelled out in the docs. You can do either:
-
在属性上使用
ResourcePath
选项.
[Required(ResourcePath = "Resources")]
然后,将本地化的消息添加到Resources/Namespace.To.MyClass.[lang].resx
.
Then, you'd add the localized message to Resources/Namespace.To.MyClass.[lang].resx
.
对所有类使用一个资源文件:
Use one resource file for all classes:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddDataAnnotationsLocalization(options => {
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResource));
});
}
这篇关于如何在ASP.NET Core中本地化验证属性的标准错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!