本地化和DataAnnotations。 GlobalResourceProxyGenerator和PublicResxFileCodeGenerator

为什么DataAnnotation属性难以访问PublicResxFileCodeGenerator创建的资源?

我发现以下属性:

[Compare("NewPassword", ErrorMessageResourceName = "RegisterModel_ConfirmPasswordError", ErrorMessageResourceType = typeof(Resources.Global))] 

如果已使用PublicResxFileCodeGenerator创建资源,将无法找到该资源。 但是,使用GlobalResourceProxyGenerator创建的相同资源将正常工作。 两个资源文件都设置为Content,并且位于App_GlobalResources中。 我已经尝试将默认语言放在App_LocalResources中,但似乎没有任何区别。 我的测试是我的第二语言(GlobalResourceProxyGenerator)工作,但我的主要语言(PublicResxFileCodeGenerator)抛出exception(它无法找到资源文件)。 如果我切换到GlobalResourceProxyGenerator然后一切都很好(但显然没有公共访问)。

有人知道为什么吗? 我想将来将资源转移到另一个程序集中。

那是因为您将资源文件放在App_GlobalResources文件夹中,该文件夹是ASP.NET中的特殊文件夹。 如果您将资源文件放在其他位置,这应该有效。 这也可能是与ASP.NET MVC应用程序完全独立的项目。

以下是您可以执行此操作的步骤:

  1. 使用默认Internet模板创建新的ASP.NET MVC 3应用程序
  2. 添加包含RegisterModel_ConfirmPasswordError资源字符串的~/Messages.resx文件
  3. 将自定义工具设置为此资源文件的PublicResXFileCodeGenerator

    在此处输入图像描述

  4. 添加模型:

     public class MyViewModel { [Compare("NewPassword", ErrorMessageResourceName = "RegisterModel_ConfirmPasswordError", ErrorMessageResourceType = typeof(MvcApplication1.Messages))] public string Password { get; set; } public string NewPassword { get; set; } } 
  5. 控制器:

     public class HomeController : Controller { public ActionResult Index() { return View(new MyViewModel()); } [HttpPost] public ActionResult Index(MyViewModel model) { return View(model); } } 
  6. 视图:

     @model MyViewModel @using (Html.BeginForm()) { 
    @Html.LabelFor(x => x.Password) @Html.EditorFor(x => x.Password) @Html.ValidationMessageFor(x => x.Password)
    @Html.LabelFor(x => x.NewPassword) @Html.EditorFor(x => x.NewPassword) @Html.ValidationMessageFor(x => x.NewPassword)
    }

然后,您可以通过提供相应的翻译开始本地化:

  • Messages.fr-FR.resx
  • Messages.de-DE.resx
  • Messages.it-IT.resx
  • Messages.es-ES.resx

更新:

我在评论部分询问了App_GlobalResources文件夹有什么特别之处,以及为什么它不能用于它。 嗯,实际上你可以让它工作。 您需要做的就是将Build Action设置为Embedded Resource 。 默认情况下,当您将文件添加到App_GlobalResources文件夹时,Visual Studio将其设置为Content ,这意味着此资源将不会合并到运行时程序集中,并且ASP.NET MVC无法找到它:

在此处输入图像描述