c# - ASP.NET Core 6 MVC 中的本地化模型数据注释

标签 c# asp.net-core-mvc

我有一个在 ASP.NET Core 6 MVC 上运行的多语言网站。

数据标注应基于用户语言;我可以使用 sharedResource 类使网站成为双语。

问题是如何让模型数据标注错误双语化;目前,我只得到了数据注释ErrorMessage

程序.cs

builder.Services.AddControllersWithViews()
             .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
              //.AddDataAnnotationsLocalization();// <--- for ERROR MSG -----
              .AddDataAnnotationsLocalization(
                 options => {
                     options.DataAnnotationLocalizerProvider = (type, factory) =>
                         factory.Create(typeof(DataAnnotationResource));
                 });// <---------- For ERROR MSG -----

工厂数据模型

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文件夹:

enter image description here

当前代码的输出

enter image description here

最佳答案

我遇到了同样的问题,我必须进行以下更改

来自

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!);
    };
});

关于c# - ASP.NET Core 6 MVC 中的本地化模型数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71294332/

相关文章:

c# - 将对象转换为继承对象

c# - 在 Windows Server 2012 上安装更多文化

c# - 在不更改 url 的情况下显示自定义页面

asp.net-core - MVC6 中的 Request.IsAjaxRequest() 替代方案

c# - 从编辑器中捕获未处理的异常

c# - 带图像的简单开/关切换按钮

c# - C#UdpClient服务器和客户端问题

c# - 以英语以外的特定语言获取 ASP.NET Core 模型错误

c# - "Cannot find compilation library location for package "enc.dll ""错误发生.net core 依赖注入(inject)

c# - 如何为验证属性提供本地化验证消息