I have an issue with language resource is not display correct value base on the culture, I have no problem with ASP.NET Core Web Application, however in the Web API it's not working correctly.
Library => .NET Core 3.1 - Class Library
Language.resx and Language.vi.resx
Web API => .NET Core 3.1
The localization middleware is enabled in the Startup.Configure method as below:
Then in controller, I'm have an action to get the current culture and the value of the resource, however it's always return the value of English
https://localhost:5051/api/home/test?culture=en-US
https://localhost:5051/api/home/test?culture=vi-VN
You need to configure localization in ASP.Net Core Web API a little bit different.
Frist of all, the main issue with folder naming and controller. You need to have the same resource naming and controller. More about in Microsoft documentation. Also, resource folder should be in the same project of ASP.Net Core Web API.
For example: HomeController and Resources/Controllers.HomeController.en-US.resx or Resources/Controllers/HomeController.en-US.resx
I have created new ASP.Net Core Web API project and do the following steps:
ConfigureServices()
add this code:services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCulters = new List<CultureInfo>()
{
new CultureInfo("en-US"),
new CultureInfo("fr-FR")
};
options.DefaultRequestCulture = new RequestCulture(supportedCulters.FirstOrDefault());
options.SupportedCultures = supportedCulters;
options.SupportedUICultures = supportedCulters;
});
Configure()
add this code:var requestLocalizationOptions = app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(requestLocalizationOptions.Value);
HomeController
:private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(IStringLocalizer<HomeController> localizer)
{
_localizer = localizer;
}
[HttpGet]
public ActionResult Get()
{
var currentLanguage = CultureInfo.CurrentCulture;
var result = $"{currentLanguage}-{_localizer["Hello"].Value}";
return Ok(result);
}
Finally, it works correct.
English text
France text
Do the following steps:
Language
in folder Resources
in your seperate project.HomeController
following codeprivate readonly IStringLocalizer<Language> _localizer;
public HomeController(IStringLocalizer<Language> localizer)
{
_localizer = localizer;
}
Finally, it works correct for separate assembly project.