ASP. NET Core MVC project for Multi-language (globalization/localization)

Source: Internet
Author: User

Just recently in the hands of a razor MVC project to achieve a multi-lingual function, called globalization or localization, whatever. The ultimate effect is to switch the entire station language with one click, and only write a set of pages when developing.

Get down to the chase.

First, we will create a Cultureconfigurer class for managing localized resources and completing the "translation" process:

I use static classes here, and then execute the init () method when the MVC project is started, which is a bit silly, but you can also write an interface and then inject the dependency into a singleton.

1 usingSystem.Collections.Generic;2 usingSystem.IO;3 usingSystem.Reflection;4 usingNewtonsoft.json;5 6 namespaceLocalization7 {8      Public enumCulture9     {Ten Cn, One En A     } -  -      Public Static classCultureconfigurer the     { -         Private Staticdictionary<string,string>_endictionary; -         Private Staticdictionary<string,string>_cndictionary; -  +          Public Static voidInit () -         { +             varAssembly = Assembly.Load (NewAssemblyName ("Localization")); A  at             varResourceNames =Assembly. GetManifestResourceNames (); -             foreach(varResourceNameinchresourcenames) -             { -                 if(Resourcename.endswith ("En-us.json") || Resourcename.endswith ("Zh-cn.json")) -                 { -                     using(varstream =Assembly. GetManifestResourceStream (resourcename)) in                     { -                         if(Stream! =NULL) to                         { +                             using(StreamReader reader =NewStreamReader (stream)) -                             { the                                 varContent =Reader. ReadToEnd (); *dictionary<string,string> localizationdictionary = $jsonconvert.deserializeobject<dictionary<string,string>>(content);Panax Notoginseng                                 if(Resourcename.endswith ("En-us.json")) -                                 { the_endictionary =localizationdictionary; +                                 } A                                 Else the                                 { +_cndictionary =localizationdictionary; -                                 } $                             } $                         } -                     } -                 } the             } -         }Wuyi  the          Public Static stringGetValue (stringkey, culture culture) -         { Wu             Switch(Culture) -             { About                  Case(culture.cn): $                     { -                         if(_cndictionary.containskey (key)) -                         { -                             return_cndictionary[key]; A                         } +                         Else the                         { -                             return$"[{key}]"; $                         } the                     } the                  Case(culture.en): the                     { the                         if(_endictionary.containskey (key)) -                         { in                             return_endictionary[key]; the                         } the                         Else About                         { the                             return$"[{key}]"; the                         } the                     } +                 default: -                     { the                         return$"[{key}]";Bayi                     } the             } the         } -     } -}
View Code

Here are a few things to note:

1. The Enum class culture is used to represent the language to be implemented, here I simply implemented the Chinese and English (other I do not understand), the corresponding Cultureconfigurer class will have Chinese and English two dictionary

2. The assembly was loaded with Assembly.Load, the parameter is your own assembly name, and I've written a random

3. resource file I chose the JSON file, also to facilitate the invocation of JS, of course, you can also use XML or any format you want to use, only need to adjust the parsing method, the contents of the file loaded into the corresponding dictionary can be

4. See the GetValue method, I believe we have already understood, in fact, the multilingual language, regardless of what language, all use a word to do key, and then call this method "translated" into the current language of the word. For example, "open" as key, then the Chinese dictionary should have a KeyValuePair is "open": "Opened", and the corresponding English should have an "open": "Open", then the culture is Chinese, the display is "open", English is "Open".

5. The resource file can be created anywhere in the assembly, and if your project has a Project.json file, add it in the buildoptions, and note that the path is modified according to its file location

"Embed": {      "include": [        "Localization/sourcefiles/*.json"      ]    }

If it is VS2017, is the csproj file, then right-click the resource file to add, select "Properties", configure Change to "all configuration", "Build Action" in the Advanced configuration property to "embedded resources", such as:

  

Here, we've written the core classes for localizing, and here's how to address the issues that appear on the page:

Create a new class in the MVC project Myrazorpage

  

1 usingSystem;2 usingMicrosoft.AspNetCore.Mvc.Razor;3 usingLocalization;4 5 namespaceMVC. views6 {7      Public Abstract classMyrazorpage<tmodel>: razorpage<tmodel>8     {9          Public Virtual stringLstringsource)Ten         { One             varValue = context.request.cookies["__culture"]; A Culture C; -             if(string. IsNullOrEmpty (value) | | ! Enum.tryparse (Value, outc)) -             { thec =culture.cn; -             } -             returnCultureconfigurer.getvalue (source, c); -         } +     } -}

Note that this class is an abstract class that inherits the Razorpage<tmodel>. Then find the _viewimports.cshtml file under the Views folder and add a line "@inherits MVC. Views.myrazorpage<tmodel> "so that all your razorpage will inherit the Myrazorpage class, which means you can write the method you want to use in Myrazorpage, It can be called directly in the cshtml. Here I write an L method that invokes the GetValue method of the Cultureconfigurer. So, the text that needs to be translated on the page is just written as @l ("Open").

As you can see, I have saved the user's language in a cookie, and here you can have their own implementation methods. My implementation method is very simple, the user switches the language when the access to an interface, modify the representative language of the cookie, and then refresh the page.

If you have any questions, please leave a comment below, this is my first blog, I hope it will be useful to everyone!

ASP. NET Core MVC project for Multi-language (globalization/localization)

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.