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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With