.Net Core Data Annotations - 共享资源的本地化 [英] .Net Core Data Annotations - localization with shared resources

查看:18
本文介绍了.Net Core Data Annotations - 共享资源的本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用共享的 resx 文件来指定所有可翻译的字符串(既是为了翻译的方便,更重要的是避免有几十个与 DRY 原则冲突的单独的 resx 文件).我让它与控制器和视图的 IStringLocalizer 一起工作,但我无法弄清楚如何为模型的数据注释实现它.

I would like to use shared resx file to specify all the translatable strings (both for translator convenience, and more importantly to avoid having dozens of separate resx files that clash with DRY principle). I got it working with IStringLocalizer for controllers and views, but I just can't figure out how to implement it for model's data annotations.

它通过使用 Models.AccountViewModels.LoginViewModel.en.resx 之类的单独文件来工作,但是我将如何使用共享资源文件而不是特定文件进行数据注释?任何人都可以分享实施示例吗?

It works by using separate files like Models.AccountViewModels.LoginViewModel.en.resx, but how would I go and use shared resource file for data annotations instead of specific ones? Can anyone share example of implementation?

附言环境是 .NET Core 1.1,因此验证和显示注释都应该在可用于本地化的版本中

P.S. Environment is .NET Core 1.1 so both validation and display annotations should be in that version available for localization

推荐答案

第 1 步:创建一个名为 ValidationMessages.cs 的简单类并将其留空.我假设您的课程位于/Validation 文件夹中.

Step 1: Create a simple class, named ValidationMessages.cs and leave it empty. I will assume that your class is located in /Validation folder.

第 2 步:将 Startup.cs 文件中数据注释本地化程序的提供程序修改为如下所示:

Step 2: Modify provider for data annotations localizer in your Startup.cs file to be like this:

mvcBuilder.AddDataAnnotationsLocalization(options => 
{
    options.DataAnnotationLocalizerProvider = (type, factory) => 
    {
        return factory.Create(typeof(ValidationMessages));
    };
});

第 3 步:在/Resources 中创建文件夹/Validation(我假设您将所有资源文件都保存在该文件夹中),然后在那里添加 ValidationMessages.fr-FR.resx 文件(即法国文化).

Step 3: Create folder /Validation in /Resources (I assume that you are keeping all resource files in that folder) and then add ValidationMessages.fr-FR.resx file there (for French culture i.e.).

第 4 步:使用您喜欢的键将条目添加到资源文件中.我假设你会有像 RequiredError、MaxLengthError 等键.

Step 4: Add entries to the resource files with keys of your liking. I assume that you will have keys like RequiredError, MaxLengthError, etc.

第 5 步:使用 [Required(ErrorMessage="RequiredError")] 装饰模型类的属性.

Step 5: Decorate properties on your model class with [Required(ErrorMessage="RequiredError")].

下次属性验证失败时,将从 ValidationMessages.{culture}.resx 文件中提取验证消息.

Next time property validation fails, validation messages will be pulled from ValidationMessages.{culture}.resx files.

但请记住,如果您使用 DisplayAttribute,不仅会搜索验证消息,还会搜索属性名称.

Keep in mind though, that not only validation messages will be searched there, but also property names if you use DisplayAttribute.

这篇关于.Net Core Data Annotations - 共享资源的本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆