ASP. Net core MVC project implements multilingual instances (Globalization / localization)

Time:2021-9-8

Just recently, I’m implementing a multilingual function for a razor MVC project, which is called globalization, localization and whatever. The final effect is to switch the language of the whole station with one click, and only need to write a set of pages when developing.

Let’s get to the point

First, we need to create a cultureconfigurer class to manage localization resources and complete the “translation” phase:

Here I use a static class, and then execute init () method during startup of MVC project. It’s actually a little stupid. Of course, you can also write an interface first and then use dependency injection to form a singleton.


using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Newtonsoft.Json;

namespace Localization
{
  public enum Culture
  {
    Cn,
    En
  }

  public static class CultureConfigurer
  {
    private static Dictionary<string, string> _enDictionary;
    private static Dictionary<string, string> _cnDictionary;

    public static void Init()
    {
      var assembly = Assembly.Load(new AssemblyName("Localization"));

      var resourceNames = assembly.GetManifestResourceNames();
      foreach (var resourceName in resourceNames)
      {
        if (resourceName.EndsWith("en-US.json") || resourceName.EndsWith("zh-CN.json"))
        {
          using (var stream = assembly.GetManifestResourceStream(resourceName))
          {
            if (stream != null)
            {
              using (StreamReader reader = new StreamReader(stream))
              {
                var content = reader.ReadToEnd();
                Dictionary<string, string> localizationDictionary =
                  JsonConvert.DeserializeObject<Dictionary<string, string>>(content);
                if (resourceName.EndsWith("en-US.json"))
                {
                  _enDictionary = localizationDictionary;
                }
                else
                {
                  _cnDictionary = localizationDictionary;
                }
              }
            }
          }
        }
      }
    }

    public static string GetValue(string key, Culture culture)
    {
      switch (culture)
      {
        case (Culture.Cn):
          {
            if (_cnDictionary.ContainsKey(key))
            {
              return _cnDictionary[key];
            }
            else
            {
              return $"[{key}]";
            }
          }
        case (Culture.En):
          {
            if (_enDictionary.ContainsKey(key))
            {
              return _enDictionary[key];
            }
            else
            {
              return $"[{key}]";
            }
          }
        default:
          {
            return $"[{key}]";
          }
      }
    }
  }
}

Here are some points to note:

1. Enum class culture is used to represent the language to be implemented. Here, I simply implemented Chinese and English (I don’t understand others). The corresponding cultureconfigurer class has two dictionaries, Chinese and English

2. Use assembly.load to load the assembly. The parameter is your own assembly name. I just write one here

3. resource file, I chose the JSON file, also to facilitate the call in JS, of course, you can also use XML or any format you want, only need to adjust the parsing method, loading the file content to the corresponding Dictionary.

The 4. is to see the GetValue method. I believe you all understand that in fact, multilingual, no matter what language, use a word to do key, and then call this method to translate into the current language. For example, with “open” as the key, there should be a keyvaluepair in the Chinese dictionary that is “open”: “open”, and there should be an “open”: “open” in the corresponding English. When the culture is Chinese, the display is “open” and the English is “open”.

5. Resource files can be created anywhere in the assembly. If your project has a project.json file, add it in buildoptions. Pay attention to modifying the path according to your file location


"embed": {
   "include": [
    "Localization/SourceFiles/*.json"
   ]
  }

If vs2017 is a csproj file, right-click the resource file to be added, select “properties”, change the configuration to “all configurations”, and change the “generation operation” in the advanced of configuration properties to “embedded resources”, as shown in the following figure:

Now that we have written the core classes for localization, we need to solve the problem of how to display them on the page:

Create a new class myrazorpage in the MVC project


using System;
using Microsoft.AspNetCore.Mvc.Razor;
using Localization;

namespace MVC.Views
{
  public abstract class MyRazorPage<TModel> : RazorPage<TModel>
  {
    public virtual string L(string source)
    {
      var value = Context.Request.Cookies["__culture"];
      Culture c;
      if (string.IsNullOrEmpty(value) || !Enum.TryParse(value, out c))
      {
        c = Culture.Cn;
      }
      return CultureConfigurer.GetValue(source, c);
    }
  }
}

Note that this class is an abstract class that inherits razorpage < tModel >. Then find it under the views folder_ Add a line “@ inherits MVC. Views. Myrazorpage < tModel >” to the viewimports.cshtml file, so that all your razorpages will inherit the myrazorpage class, that is, you can write the methods you want in myrazorpage and call them directly in cshtml. Here I wrote an L method and called the getValue method of cultureconfigurator. Then, the text to be translated on the page can be written as @ L (“open”).

As you can see, I save the user language in cookies. Here you can have your own implementation methods. My implementation method is very simple. When users switch languages, they access an interface, modify the cookie representing the language, and then refresh the page.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

Beautify your code VB (VBS) code formatting implementation code

However, vb.net does have many new functions that VB6 does not have. The automatic typesetting of code is one, which is the function we want to realize today – VB code formatting.Let’s look at the effect: Before formatting: Copy codeThe code is as follows: For i = 0 To WebBrowser1.Document.All.length – 1 If WebBrowser1.Document.All(i).tagName = […]