1

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

Benjamin Martin
  • 576
  • 1
  • 8
  • 27

2 Answers2

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://learn.microsoft.com/en-gb/dotnet/standard/attributes/writing-custom-attributes

Hopefully, it helps. :)

MeDead
  • 197
  • 2
  • 9
  • Hi NiceBone, thank you very much for the answer. But i really dont want to create a new Attribute each time. If there is a need to do so, then i would prefer using fluent.validation and then inject IStringLocalizer in the validation process. I saw ppls using services.AddMVC().AddLocalization(). But this doesnt work for web api. – Benjamin Martin Aug 19 '21 at 08:11
  • Unfortunately I can't tell you more than the method I described above. So far I have done everything with the attribute "LocalizedDisplayName". Maybe someone else has a solution :) – MeDead Aug 19 '21 at 09:52
0

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.

Daniel Ashraf
  • 31
  • 1
  • 8