Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all keys in ResourceManager

Tags:

asp.net-core

Recently I've created a new ASP.NET Core Web Application and one of my requirements is to expose an endpoint for clients to get all the translation keys and values stored in .resx files.

Before ASP.NET Core I was able to do something like this. But the command ResourceManager.GetResourceSet() is not recognized anymore:

public IActionResult Get(string lang)
{
    var resourceObject = new JObject();

    var resourceSet = Resources.Strings.ResourceManager.GetResourceSet(new CultureInfo(lang), true, true);
    IDictionaryEnumerator enumerator = resourceSet.GetEnumerator();
    while (enumerator.MoveNext())
    {
        resourceObject.Add(enumerator.Key.ToString(), enumerator.Value.ToString());
    }

    return Ok(resourceObject);
}

Are there any new ways to get all keys and values of a resource in ASP.NET Core Project?

like image 550
Sobhan Avatar asked Dec 23 '22 21:12

Sobhan


1 Answers

If you will look at the documentation, you will see that ASP.NET Core Team has introduced IStringLocalizer and IStringLocalizer<T>. Under the cover, IStringLocalizer use ResourceManager and ResourceReader. Basic usage from the documentation:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;

namespace Localization.StarterWeb.Controllers
{
    [Route("api/[controller]")]
    public class AboutController : Controller
    {
        private readonly IStringLocalizer<AboutController> _localizer;

        public AboutController(IStringLocalizer<AboutController> localizer)
        {
            _localizer = localizer;
        }

        [HttpGet]
        public string Get()
        {
            return _localizer["About Title"];
        }
    }
}

For getting all keys you can do that:

var resourceSet = _localizer.GetAllStrings().Select(x => x.Name);

But for getting all keys by language, you need to use WithCulture method:

var resourceSet = _localizer.WithCulture(new CultureInfo(lang))
                            .GetAllStrings().Select(x => x.Name);

So when you inject IStringLocalizer into your controller it will be instantiated as an instance of ResourceManagerStringLocalizer class with default CultureInfo for your application, and for getting resources specific for your lang variable, you need to use WithCulture method, because it creates new ResourceManagerStringLocalizer class for a specific CultureInfo.

like image 166
ivamax9 Avatar answered Feb 08 '23 12:02

ivamax9