This is a demo project base on .NET core WebAPI template WeatherForecast, implement Localization on Text and Enum, read i18n text from resources.
- Add resource file(.resx)
Usually I will put my resource file in [Resources] folder, remember put cultureInfo name on resx file like this{name}.{culture}.resx
- Setup Startup.cs
Inpublic void ConfigureServices(IServiceCollection services)
add following code//set Support Cultures and default services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[]{ new CultureInfo("en-US"), new CultureInfo("zh-TW"), new CultureInfo("ja-JP") }; options.DefaultRequestCulture = new RequestCulture("en-US"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); //set resource path services.AddLocalization(options => options.ResourcesPath = "Resources");
- Setup controller
- DI
private readonly IStringLocalizer _localizer; public YourController(IStringLocalizerFactory factory) { _localizer = factory.Create("Message", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); }
- Get Value
using_localizer[{name}]
to get the value from resource file, for example,_localizer["cold"]
can get key name [cold]'s culture string, if can't find the key in resource, it will just output the key name "cold" as string.
You can check WeatherForecastController.cs for more usage detail.
- DI
- Enum with i18N
It was easy, just use_localizer[{enumName}.ToString()]
to get culture string from resource, or you can check here for the usage.