如何在 ASP.NET Core 6 MVC 中添加默认数据注释验证错误消息的本地化?

问题描述 投票:0回答:1

这个想法是利用默认消息来快速开发应用程序和使代码更简洁,但我无法找到一种方法来做到这一点。

这就是我已经走了多远:

// Program.cs:
using ...
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddLocalization(o => o.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews()
    .AddDataAnnotationsLocalization(o => {
        o.DataAnnotationLocalizerProvider = (type, factory) =>
        {
            var assemblyName = new AssemblyName(typeof(SharedResources).GetTypeInfo().Assembly.FullName!);
            return factory.Create("SharedResources", assemblyName.Name!);
        };
    });
...
var app = builder.Build();
...
var supportedCultures = new[] { "en-US", "es-CL" };
var localizationOptions = new RequestLocalizationOptions()
    .SetDefaultCulture("es-CL")
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
...
app.Run();

型号:

namespace WebApplication1.Models
{
    public class Cliente
    {
        public int Id { get; set; }

        [Required]
        [StringLength(100)]
        public string Nombre { get; set; } = null!;

        [StringLength(100)]
        public string? Apellido { get; set; }

        [EmailAddress]
        public string? Email { get; set; }

        [Phone]
        public string? Telefono { get; set; }
    }
}

使用资源文件,我尝试了一堆不同的键,但没有一个有效:

// SharedResources.cs:
public class SharedResources { /* empty class */ }

// SharedResources.en-US.resx:
"Required"                          "The {0} field is required."
"RequiredAttribute"                 "The {0} field is required."
"RequiredAttribute_ValidationError" "The {0} field is required."
"The {0} field is required."        "The {0} field is required."
"The0FieldIsRequired"               "The {0} field is required."
"TheFieldIsRequired"                "The {0} field is required."

// SharedResources.es-CL.resx:
"Required"                          "El campo {0} es requerido."
"RequiredAttribute"                 "El campo {0} es requerido."
"RequiredAttribute_ValidationError" "El campo {0} es requerido."
"The {0} field is required."        "El campo {0} es requerido."
"The0FieldIsRequired"               "El campo {0} es requerido."
"TheFieldIsRequired"                "El campo {0} es requerido."

只有当我像这样声明属性时它才有效:

[Required(ErrorMessage = "The {0} field is required.")]

但是我需要像下面这样声明它,以实现快速开发和更清晰的代码:

[Required]
asp.net-core-mvc localization .net-6.0 data-annotations
1个回答
0
投票

恐怕你的要求无法实现。

我们这里有一个文档提到了

If the localized value of "About Title" isn't found, then the indexer key is returned, that is, the string "About Title".
,我认为这意味着我们需要一个密钥来在资源文件中搜索以获得替换作为响应。

我用你的代码片段在我这边测试,我发现我使用了

[Required(ErrorMessage = "Required")]
,那么输出将是所需的本地化内容。

由于我们不能将

Name
列留空,所以恐怕我们必须定义一个“键”,然后在数据注释中使用这个键才能使其工作。

© www.soinside.com 2019 - 2024. All rights reserved.