使用App_GlobalResources在ASP.NET MVC 4中进行本地化

and*_*uta 7 asp.net localization app-globalresources asp.net-mvc-4

我想完成两件事:

  1. 本地化"FieldMustBeDate"和"FieldMustBeNumeric"的"内置"错误消息.
  2. 本地化您将遇到的一些其他错误消息,例如"PropertyValueRequired".

通过对问题1 使用http://forums.asp.net/t/1862672.aspx/1MVC 4忽略问题2的DefaultModelBinder.ResourceClassKey,我已经设法让两者都在本地工作.

但是,一旦我发布到网站,"内置"错误消息默认返回到英语,而其他错误消息保持本地化.

我已经阅读了几个应该避免使用App_GlobalResources的地方,但是我不能在不使用它的情况下完成问题1.

我创建了一个名为"WebResources.resx"的.resx文件,将Build Action设置为"Embedded",将Copy to Output Directory设置为"Do no Copy",将Custom Tool设置为"PublicResXFileCodeGenerator"并设置Custom工具命名空间为"资源".项目本身设置为仅发布所需的文件.

我的Global.asax.cs包含以下(相关)代码:

  ClientDataTypeModelValidatorProvider.ResourceClassKey = "WebResources";  
  DataAnnotationsModelValidatorProvider.RegisterAdapter(
  typeof(RequiredAttribute),
  typeof(MyRequiredAttributeAdapter));
Run Code Online (Sandbox Code Playgroud)

类MyRequiredAttributeAdapter包含以下代码:

public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
    public MyRequiredAttributeAdapter(
        ModelMetadata metadata,
        ControllerContext context,
        RequiredAttribute attribute
    )
        : base(metadata, context, attribute)
    {
        if (attribute.ErrorMessageResourceType == null)
        {
            attribute.ErrorMessageResourceType = typeof(Resources.WebResources);
        }
        if (attribute.ErrorMessageResourceName == null)
        {
            attribute.ErrorMessageResourceName = "PropertyValueRequired";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在本地工作但是有没有人知道如何在发布之后让"内置"消息工作?

谢谢您的帮助!

最好的问候,安德烈亚斯

and*_*uta 5

我自己想出了这个.如果您尝试完成上述操作,则必须分离本地化的错误消息.

为其他错误消息fx"PropertyValueRequired"创建*.resx文件并将Build Action设置为"Embedded",将Copy to Output Directory设置为"Do no Copy",将Custom Tool设置为"PublicResXFileCodeGenerator"并设置Custom工具命名空间为"资源".

在我的情况下,我已将"PropertyValueRequired"移动到名为LocalDanish.resx的文件(仍在App_GlobalResources文件夹中)并更改了我的"MyRequiredAttributeAdapter"中的行

attribute.ErrorMessageResourceType = typeof(Resources.WebResources);
Run Code Online (Sandbox Code Playgroud)

attribute.ErrorMessageResourceType = typeof(Resources.LocalDanish);
Run Code Online (Sandbox Code Playgroud)

为了使"内置"错误消息起作用,您必须创建两个*.resx文件.我创建了WebResources.resx和WebResources.da.resx.不要更改任何内容,默认情况下保留它们的设置(Build Action to"Content"等).我想网站会自动查找我的案例中的*.da.resx文件,因为我在WebConfig中设置了全球化:

<globalization uiCulture="da-DK" culture="da-DK"/>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助任何人.

最好的问候,安德烈亚斯