The Asp. Net Core MVC project implements multi-language instances (Globalization/Localization) and mvclocalization.

Source: Internet
Author: User

The Asp. Net Core MVC project implements multi-language instances (Globalization/Localization) and mvclocalization.

Recently, we have implemented a multi-language function for a Razor MVC project, such as Globalization, Localization, and whatever. The final result is to switch the full-site language with one click, and you only need to write a set of pages during development.

Enter the subject

First, we need to create a culturecycler class to manage local resources and complete the "Translation" process:

Here I use static classes and execute the Init () method when the MVC project StartUp. It is actually a bit silly. Of course you can also write an interface and inject it into a singleton with dependencies.

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}]";          }      }    }  }}

Note the following points:

1. The enum class Culture is used to represent the language to be implemented. Here I simply implement both Chinese and English (I do not understand other languages). The corresponding culturecycler class has two dictionaries: Chinese and English.

2. I used Assembly. Load to Load the Assembly. The parameter is your own Assembly name. Here I just wrote

3. I chose a json file for resource files to facilitate js calls. Of course, you can also use xml or any format you want to use. You only need to adjust the resolution method, load the file content to the corresponding Dictionary.

4. When we see the GetValue method, I believe everyone understands it. In fact, multiple languages use a word as the key no matter what language they use, and then call this method to "translate" the words in the current language. For example, if "Open" is used as the Key, a KeyValuePair in the Chinese Dictionary is "Open": "Open", and an "Open" in the corresponding English should be displayed ": "Open", the "Open" and "Open" are displayed in the "Culture" text ".

5. The resource file can be created anywhere in the Assembly. If your project has a project. json file, add it in buildOptions. Note that you can modify the path based on your file location.

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

If VS2017 is a csproj file, right-click the resource file to be added, select "attribute", and change the configuration to "All configurations ", in the advanced configuration attributes, modify "generate operation" to "embedded resource", for example:

At this point, we have written the core class for localization. The following describes how to display the content 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>. Find _ ViewImports in the Views folder. add a line "@ inherits MVC" to the cshtml file. views. myRazorPage <TModel> ", so that all your razorpages will inherit the MyRazorPage class. That is to say, you can write the method you want in MyRazorPage and call it directly in cshtml. Here I wrote an L method and called the GetValue METHOD OF THE CultureConfigurer. The text to be translated on the page can be written as @ L ("Open.

As you can see, I saved the user language in the Cookie. Here you can have their own implementation methods. My implementation method is very simple. When you switch the language, you access an interface, modify the Cookie representing the language, and then refresh the page.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.