.net.net-coreasp.net-core-localization

Why IStringLocalizer sometimes returns object but sometimes returns string


I caanot understand one thing in IStringLocalizer. Let suppose I have an endpoint that returns Status code 200 and some localized string.


public async Task<IActionResult> Test()
{
   return Ok(localizer["Localized Text"])
}

if I do this way I will receive an object with some information about this localizer

{
  "name": "Localized Text",
  "value": "Localized Text translated",
  "resourceNotFound": false,
  "searchedLocalization": "MyApi.Translations"
}

in order to be string with translated text returned, I need to add .Value


public async Task<IActionResult> Test()
{
   return Ok(localizer["Localized Text"].Value)
}

(this returns only 'Localized Text translated')

BUT If I have some class that has a string property

public class ResponseMessage {
   public string Message {get; set;}
}

and I assign localizer to its string property, then I dont have to add .Value in order to receive corresponding translation

public async Task<IActionResult> Test()
{
   return Ok(new ResponseMessage {
      Message = localizer["Localized Text"]
   })
}

I would like to know, where in documentation this behavior is described. Cause for now it looks like a magic.


Solution

  • The IStringLocalizer indexer returns an instance of LocalizedString, which is what's serialized when you return it directly in your first example.

    For your other scenarii, the LocalizedString is implicit converted to a string via its implicit conversion operator. I assume the implicit conversion operator simply returns the LocalizedString value.

    You can check the User-defined conversion operators page to learn more about implicit conversion.