本地化和DataAnnotations.GlobalResourceProxyGenerator和PublicResxFileCodeGenerator

Qui*_*ome 23 c# asp.net-mvc localization

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

我发现以下属性:

[Compare("NewPassword", ErrorMessageResourceName = "RegisterModel_ConfirmPasswordError", ErrorMessageResourceType = typeof(Resources.Global))]
Run Code Online (Sandbox Code Playgroud)

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

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

Dar*_*rov 20

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

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

  1. 使用默认Internet模板创建新的ASP.NET MVC 3应用程序
  2. 添加~/Messages.resx包含RegisterModel_ConfirmPasswordError资源字符串的文件
  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; }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 控制器:

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

    @model MyViewModel
    
    @using (Html.BeginForm())
    {
        <div>
            @Html.LabelFor(x => x.Password)
            @Html.EditorFor(x => x.Password)
            @Html.ValidationMessageFor(x => x.Password)
        </div>
    
        <div>
            @Html.LabelFor(x => x.NewPassword)
            @Html.EditorFor(x => x.NewPassword)
            @Html.ValidationMessageFor(x => x.NewPassword)
        </div>
    
        <button type="submit">OK</button>
    }
    
    Run Code Online (Sandbox Code Playgroud)

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

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

更新:

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

在此输入图像描述