我应该尝试实现的是在 中为每种支持的语言提供一个资源 (resx) 文件。网核 .我稍微解释一下这个问题。
我的每个实体上都有 DataAnnotations,我需要本地化在出现错误时返回的消息。似乎 所需的默认约定网核是为我们的每个实体都有一个不同的 resx 文件。
该文件根据具有区域性标识符和 resx 扩展名的实体的命名空间进行命名。因此,如果我在命名空间 Data.Entities 中有一个名为 Customers 的实体,我应该添加一个名为 Data.Entities.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 文件中。
但是,如果我继续使用像供应商这样的另一个实体,我将被迫编写另一个名为 Data.Entities.Suppliers.it.resx 的资源文件,当然我有
StringLength(50, ErrorMessage="The {0} should not be longer than {1} characters")
public string SupplierName {get;set;}
现在我需要在供应商实体的正确文件中再次编写相同的翻译。这也适用于其他常见属性,如 [Required]。
所以我希望能很好地解释我的问题,我的问题是:有一种方法可以为我的所有实体验证消息指定一个资源文件,然后为公共(public)文本编写一次消息?
最佳答案
来自 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 useSharedResource
, rather than the resource for each class.
关于asp.net-core - 用于 DataAnnotations 本地化的单个资源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45373658/