简体   繁体   中英

ASP.NET Core resource localization at runtime

I am trying to localize a hosted service in response to a runtime condition which is fed in a variable lang , which represents a 2-letter ISO code (such as 'en', 'es', ...).

I set the localization service in my Startup.cs like this:

services.AddLocalization(options => { options.ResourcesPath = "xresx"; });

In my controller I have the following code:

Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lang);

I know this works, because when I pass in lang='es' the following:

var check = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

returns the correct value check = 'es' .

But then the next statement:

var msg = Resources.TestMsg

picks up my the value from my English resource file Resource.resx instead of Resource.es.resx .

What am I doing wrong, and how can I make it work? Thanks!

OK, so what ultimately worked for me was following exactly the steps in this guide: https://joonasw.net/view/aspnet-core-localization-deep-dive

OK, so what ultimately worked for me was following exactly the steps in this guide: https://joonasw.net/view/aspnet-core-localization-deep-dive

This link is the only source I've found that worked for me, and it was better than Microsoft's own documentation (which omits potential pitfalls like not naming your Resource files a very certain way).

Let me summarize some points:

  1. One needs to inject the IStringLocalizer into the Controller, eg: IStringLocalizer<MyController> _localizer;
  1. Then inside the controller you can localize your strings, eg: _localizer["STRINGKEY"] where STRINGKEY is a key from your resource file.

  2. Make sure to name your resource files properly. This is very important and is not documented by Microsoft as far as I know. Cost me a lot of time until I stumbled over the web link I've referenced above: I was naming my files like this: Resource.resx, Resource.es.resx etc and the localized wasn't finding the values, instead just returning the key itself. Eg, _localizer["STRINGKEY]" would return "STRINGKEY" rather than the corresponding value in the resource file. So you must name your files instead using your Controller's name, like this: Controllers.MyController.resx, Controllers.MyController.es.resx

These are the main points to remember. Sadly, Microsoft documentation glosses over a lot of this stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM