.Net核心数据注释-使用共享资源进行本地化 [英] .Net Core Data Annotations - localization with shared resources

查看:182
本文介绍了.Net核心数据注释-使用共享资源进行本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用共享的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 ?

提前谢谢!

P.S.环境是.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核心数据注释-使用共享资源进行本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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