Skip to content

died/.NET-Core-Localization-and-Enum

main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 

.NET Core Localization and Enum

This is a demo project base on .NET core WebAPI template WeatherForecast, implement Localization on Text and Enum, read i18n text from resources.


  1. 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
    img
  2. Setup Startup.cs
    In public 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");
  3. 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.
  • 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.

That's all.

About

Just a .NET Core Localization and Enum demo

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages