DEV Community

loading...

Dotnet Core Localization

Emre Erkoca
・3 min read

I had to make a multi-language application. Because there are a lot of languages and you might want to be global for more customers. I wanted to write a simple example before localization. I read documents and I felt a little bit confused. Then, I wanted to share my sample code.

You can store your text messages in a resource file. A resource record is composed of two parts. Name and value. Actually, there is one more part (comment) but probably you won’t use this part.

An example resource file looking like this:

Screenshot (1)

You can create resource files for different languages.
Resource.resx, Resource.de.resx, Resource.es.resx, etc.

If you want to apply localization properly, names must be same in your resource files. When the localizer doesn't find resource content, it returns null. I’ll explain this project step by step. https://github.com/emreerkoca/LocalizationExample It’s a simple Dotnet Core Web Api project.

  1. Add Resources folder to your project.
  2. Add your resource files.

Screenshot (2)

  1. Add a new folder to your project as “Localize” and add a public class to Localize folder.
namespace LocalizationExample.Localize
{
    public class Resource
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

If you want you can use different names but your resource names and your resources must be suitable. You will reach resource content through this empty class.

Resource name: Localize.Resource.de.resx
The namespace of your class is LocalizationExample.Localize and the class name is Resource.cs

  1. Startup Configuration

Add this code block to into boldConfigureServices(IServiceCollection services)bold method in Startup.cs file.

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

services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[]
    {
        new CultureInfo("en-US"),
        new CultureInfo("de")
    };

    options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});
Enter fullscreen mode Exit fullscreen mode

It’s about adding supported languages for localizers. Showing your resource files. Selecting default language.

Add this code block to boldConfigure(IApplicationBuilder app, IWebHostEnvironment env)bold method.

var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
Enter fullscreen mode Exit fullscreen mode

It’s for automatically setting culture info for your localizer. You can set culture info by any request header value.

  1. Showing Localized Messages

I used IStringLocalizer interface for reaching resource files. You can see an example usage here. Add dependencies and call the resource field name.

private readonly IStringLocalizer<Resource> _stringLocalizer;

public HomeController(IStringLocalizer<Resource> stringLocalizer)
{
    _stringLocalizer = stringLocalizer;
}

[HttpGet]
public string Get()
{
    var value = _stringLocalizer["Hello"];

    return value;
}
Enter fullscreen mode Exit fullscreen mode

Get() method will return “Hello!” because English is the default culture and English resource value is “Hello!” When you add “culture=de” to your request URL, you’ll change the culture as “de” and you’ll see “Hallo!” message.

If you want you can detect the current language from “Accept-Language” header. You can change your configuration.

Change your ConfigureServices configuration part like this:

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers();

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

     services.Configure<RequestLocalizationOptions>(options =>
     {
         var supportedCultures = new[]
         {
             new CultureInfo("en-US"),
             new CultureInfo("de")
         };

         options.SupportedCultures = supportedCultures;
         options.SupportedUICultures = supportedCultures;

         options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
         {
             var languages = context.Request.Headers["Accept-Language"].ToString();
             var currentLanguage = languages.Split(',').FirstOrDefault();
             var defaultLanguage = string.IsNullOrEmpty(currentLanguage) ? "en-US" : currentLanguage;

             if (defaultLanguage != "de" && defaultLanguage != "en-US")
             {
                 defaultLanguage = "en-US";
             }

             return Task.FromResult(new ProviderCultureResult(defaultLanguage, defaultLanguage));
         }));
     });
 }
Enter fullscreen mode Exit fullscreen mode

It’s reading the “Accept-Language” header value and getting the default language. Put a breakpoint after the language variable and see values. It’s changeable for different browser languages. If you feel confused when you read CustomRequestCultureProvider, ProviderCultureResult, etc. you can read them from official Microsoft documents.

Now, you don’t have to add a culture parameter to request URL. You can try to get values from English and German browsers.

You can read this document for detailed information.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-5.0

I have nothing to say after this. I hope it might be helpful.

Discussion (0)