'How to use localization with data annotation in a separate DTO Assembly (Asp.net Core Web Api)

I have:

  • a Dto.Library (.Net 5 Library)
  • a SharedResourceLibrary with Resource.resx (.Net 5 Library)

How can i use the Resource File Messages in conjunction with Data Annotation in my DTO.Library?

The ErrorMessage should be the text from the resx files:

public class MeterForCreationDto
{
    [Required(ErrorMessage = "Name must not be empty!")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Unit must not be empty!")]
    public string Unit { get; set; }
}

SharedResourceLibrary: looks like this answer @Shiran Dror



Solution 1:[1]

You can create a custom attribute for the properties. Something like this:

public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string resourceKey) 
        : base(GetMessageFromResource(resourceId))
    { }

    private static string GetMessageFromResource(string resourceKey)
    {
        // return the translation out of your .rsx files
    }
}

and then you need to add

public class MeterForCreationDto
{
    [LocalizedDisplayName("Name")]
    public string Name { get; set; }

    [LocalizedDisplayName("Unit")]
    public string Unit { get; set; }
}

but you need to add exactly the same key in the attribute which is in your .rsx file. If your searching for "asp.net localizeddisplayname" there are a lot of different sites with examples.

Some help for creating custom attributes: https://docs.microsoft.com/en-gb/dotnet/standard/attributes/writing-custom-attributes

Hopefully, it helps. :)

Solution 2:[2]

you can use:
[Required(ErrorMessageResourceName ="NameInRecourseFile",ErrorMessageResourceType =typeof(RecourseFileName))]
also u need to make the Recourse file public from this menu:
enter image description here
finally u need to have a default Resource file[for your default culture]
Default resource file name shouldn't have any specific culture (.en?.fr?....)
SharedService.en.resx => SharedService.resx
note .en is the default culture in your app
so it will like these:
SharedService.resx[for your default culture]
SharedService.ar.resx
SharedService.fr.resx
Hope this helped you.
Best wishes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MeDead
Solution 2 Daniel Ashraf