Localization of RequiredAttribute in ASP.NET Core 2.0

前端 未结 4 632
一生所求
一生所求 2021-01-02 03:37

I\'m struggling with localization in my new .NET Core project. I have 2 projects:

  • DataAccess project with Models and DataAnnotations (e.g. RequiredAttribute)
4条回答
  •  臣服心动
    2021-01-02 04:36

    I tried setting the ErrorMessageResourceName and ErrorMessageResourceType to my shared resource file name "Strings.resx" and "Strings.de.resx" in the DataAccess project:

       [Required(ErrorMessageResourceName = "RequiredAttribute_ValidationError", ErrorMessageResourceType = typeof(Strings))]
    

    I also tried the setting name to be RequiredAttribute_ValidationError - but it's not working.

    You were on the right track, but you don't necessarily need to set ErrorMessageResourceName / ErrorMessageResourceType properties.

    Was we can see in the source code of ValidationAttributeAdapter, the conditions to use the _stringLocalizer verison is when ErrorMessage is not null and ErrorMessageResourceName/ErrorMessageResourceType are null.

    In other words, when you don't set any properties or only ErrorMessage. So a plain [Required] should just work (see source where is passed to the base classes constructor).

    Now, when we look at the DataAnnotations resource file we see that the name is set to "RequiredAttribute_ValidationError" and the value to "The {0} field is required." which is the default English translation.

    Now if you use "RequiredAttribute_ValidationError" with the German translation in your "Strings.de-DE.resx" (or just Strings.resx as fallback), it should work with the corrected namespace from the comments.

    So using the above configuration and the strings from the GitHub repository you should be able to make the localization work without extra attributes.

提交回复
热议问题