DataAnnotations 本地化的单个资源文件

Single resource file for DataAnnotations localization

我应该尝试实现的是在 net-core 中为每种支持的语言提供一个资源 (resx) 文件。我稍微解释一下问题。

我的每个实体都有 DataAnnotations,我需要本地化返回的消息以防出现错误。 net-core 要求的默认约定似乎是为我们的每个实体提供不同的 resx 文件。

此文件根据具有文化标识符和 resx 扩展名的实体的名称空间命名。因此,如果我在命名空间 Data.Entities 中有一个名为 Customers 的实体,我应该添加一个名为 [ 的文件=42=].Customers.it.resx 并将所有意大利语翻译放入其中。所以,如果我有一个属性

StringLength(50, ErrorMessage="The {0} should not be longer than {1} characters") 
public string Name {get;set;}

然后我将正确的翻译添加到 Data.Entities.Customers.it.resx 文件中。

但是,如果我继续像 Suppliers 这样的实体,我将被迫编写另一个名为 Data.Entities.Suppliers.it.resx 的资源文件 当然还有

StringLength(50, ErrorMessage="The {0} should not be longer than {1} characters") 
public string SupplierName {get;set;}

现在我需要在 Suppliers 实体的正确文件中再次编写相同的翻译。这也适用于其他常见属性,例如 [Required].

所以我希望已经很好地解释了我的问题,我的问题是:有一种方法可以为我的所有实体验证消息指定一个资源文件,然后为通用文本编写一次消息?

docs 开始,您可以告诉框架使用共享资源进行数据注释本地化:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddDataAnnotationsLocalization(options => {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResource));
        });
}

In the preceeding code, SharedResource is the class corresponding to the resx where your validation messages are stored. With this approach, DataAnnotations will only use SharedResource, rather than the resource for each class.