ASP.NET 5 MVC6中数据模型注释的本地化和国际化

时间:2016-02-21 19:28:17

标签: localization internationalization asp.net-core asp.net-core-mvc

我正在尝试使用数据模型注释进行本地化。

更新:添加了示例代码并更改了示例以反映代码

我准备了一个小的非工作示例,可以从这里克隆https://bitbucket.org/feradz/dataannotationlocalization.git

要加载页面,请浏览到http://localhost:6092/PersonalInfo/Edit

我有以下课程:

public class PersonalInfo 
{
    [Display(Name = "NameDisplay", ResourceType = typeof(PersonalInfo))]
    [Required(ErrorMessageResourceName = "NameRequired", ErrorMessageResourceType = typeof(PersonalInfo))]
    public string Name { get; set; }
}

我在目录DataAnnotationLocalization.ViewModels.Member.PersonalInfo.resx中创建了DataAnnotationLocalization.ViewModels.Member.PersonalInfo.es.resxResources个资源文件。

DataAnnotationLocalization.ViewModels.Member.PersonalInfo.resxDataAnnotationLocalization.ViewModels.Member.PersonalInfo.es.resx我分别定义了NameDisplay=Name ENNameDisplay=Name ES

当我尝试加载页面时,我收到以下错误。

An unhandled exception occurred while processing the request.

InvalidOperationException: Cannot retrieve property 'Name' because localization failed. Type 'DataAnnotationLocalization.ViewModels.Member.PersonalInfo' is not public or does not contain a public static string property with the name 'resourceNameKey'.
System.ComponentModel.DataAnnotations.LocalizableString.<>c__DisplayClass12_0.<GetLocalizableValue>b__1()

在ASP.NET 5 MVC6中是否有任何开箱即用的支持?

2 个答案:

答案 0 :(得分:2)

它所查找的资源是您的类,而不是您的资源,因为资源和类具有相同的名称:

public class PersonalInfo
{
    [Display(Name = "resourceNameKey", ResourceType = type(PersonalInfo))]
    public Title { get; set; }
}

您可以通过明确说出命名空间来解决此问题:

public class PersonalInfo
{
    [Display(Name = "resourceNameKey", ResourceType = type(Namespace1.Namespace2.PersonalInfo))]
    public Title { get; set; }
}

更新

使您的示例有效:

namespace DataAnnotationLocalization.ViewModels.Member
{
    public class PersonalInfo
    {
        [Display(Name = "NameDisplay", ResourceType = typeof(DataAnnotationLocalization.Resources.DataAnnotationLocalization_ViewModels_Member_PersonalInfo))]
        [Required(ErrorMessageResourceName = "NameRequired", ErrorMessageResourceType = typeof(DataAnnotationLocalization.Resources.DataAnnotationLocalization_ViewModels_Member_PersonalInfo))]
        public string Name { get; set; }
    }
}

如果您重命名资源文件,那么最好的方法就是不要将名称与您使用它的类名混淆。

答案 1 :(得分:1)

问题出在资源类中。

如果使用Visual Studio添加资源,它将生成具有内部类修饰符和内部属性的Resource类。每个资源键的修饰符。

快速修复:您应该打开资源类(与附加&#39; Designer.cs&#39;的资源文件同名)并更改内部&#39;公共&#39;。每次在资源文件中添加新密钥时都必须这样做。这是Visual Studio 2015中的错误。