我有一个运行在ASP.NET Core6MVC上的多语言站点。
数据注释应该基于用户语言,我可以使用sharedResource类使站点双语。
问题是如何使模型数据标注错误双语;目前,我只得到了数据标注ErrorMessage。
Program.cs
builder.Services.AddControllersWithViews()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
//.AddDataAnnotationsLocalization();// <--- for ERROR MSG -----
.AddDataAnnotationsLocalization(
options => {
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(DataAnnotationResource));
});// <---------- For ERROR MSG -----FactoryData模型
public class FactoryData
{
[Required(ErrorMessage = "General.RequiresMessageOOO")]
public string NameInAr { get; set; }
[Required(ErrorMessage = "General.RequiresMessageOOO")]
[MaxLength(2, ErrorMessage = "General.MaxlengthExceededOOO")]
public string NameInEn { get; set; }
[Required]
[Range(1,3)]
public string Age { get; set; }
}这是localizationResource文件夹:

此当前代码的输出。

发布于 2022-02-28 12:41:49
您可以以这种方式使用DataAnnotations中的资源:
[Required(ErrorMessageResourceName = "General.RequiresMessageOOO", ErrorMessageResourceType = typeof(SharedResource))]
[MaxLength(2, ErrorMessageResourceName = "General.MaxlengthExceededOOO", ErrorMessageResourceType = typeof(SharedResource))]
public string NameInEn { get; set; }在您的SharedResource.resx文件中:
<data name="General.RequiresMessageOOO" xml:space="preserve">
<value>This field must not be empty</value>
</data>
<data name="General.MaxlengthExceededOOO" xml:space="preserve">
<value>The value exceeded the max lenght</value>
</data>在我的应用程序中,我为每种语言提供了几个SharedResource文件:

您可以在Microsoft文档中获得更多有关本地化的详细信息:ASP.NET核心的全球化与本土化
发布于 2022-07-21 05:05:50
我遇到了同样的问题,我必须做以下更改
从…
builder.Services.AddControllersWithViews()
.AddDataAnnotationsLocalization(opt =>
{
opt.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource));
});至
builder.Services.AddControllersWithViews()
.AddDataAnnotationsLocalization(opts =>
{
opts.DataAnnotationLocalizerProvider = (type, factory) =>
{
var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName!);
return factory.Create(nameof(SharedResource), assemblyName.Name!);
};
});https://stackoverflow.com/questions/71294332
复制相似问题