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



我正在尝试将本地化与数据模型注释一起使用。

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

我准备了一个小的不工作的例子,可以从这里克隆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; }
}

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

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 中是否有任何开箱即用的支持?

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

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; }
    }
}

最好是重命名资源文件,这样名称就不会与您正在使用它的类名混淆。

问题出在资源类中。

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

快速修复:应打开资源类(与附加"Designer.cs"的资源文件同名)并将"内部"更改为"公共"。并且每次将新密钥添加到资源文件时都必须执行此操作。这是Visual Studio 2015中的错误。

最新更新