asp.net-core - 用于 DataAnnotations 本地化的单个资源文件

标签 asp.net-core localization asp.net-core-mvc data-annotations

我应该尝试实现的是在 中为每种支持的语言提供一个资源 (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 use SharedResource, rather than the resource for each class.

关于asp.net-core - 用于 DataAnnotations 本地化的单个资源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45373658/

相关文章:

localization - 打开时更改 Paint.net UI 的语言

c# - ASP.NET Core API 的 ProducesResponseType 属性中包含的正确类型是什么?

c# - ASP.Net Core 客户端验证 : is there a "validation succeeded" DOM event?

asp.net-core - .NET 核心 Web api 向客户端发送错误请求

iphone - 如何在iPhone应用程序中设置英语以外的基本语言?

iphone - 波兰语的 CFStringEncoding 是什么?

dependency-injection - 从范围服务工厂获取主机名

asp.net-core - Microsoft.AspNet.Identity vnext 中的 UserValidator

validation - 在 ASP.NET Core 中禁用客户端表单验证

c# - 简单注入(inject)器注入(inject) PageModel ASP.NET Core Razor 页面