正好最近手上在给一个Razor MVC项目实现一个多语言功能,叫Globalization也好,Localization也好,whatever。最终要实现的效果呢,就是一键切换全站语言,并且开发的时候只需要写一套页面。
下面进入正题
首先,我们要创建一个CultureConfigurer类,用于管理本地化资源,完成“翻译”环节:
这里我用了静态类,然后在MVC项目StartUp的时候执行Init()方法,其实有点蠢,当然你们也可以先写一个接口然后用依赖注入成单例。
1 using System.Collections.Generic; 2 using System.IO; 3 using System.Reflection; 4 using Newtonsoft.Json; 5 6 namespace Localization 7 { 8 public enum Culture 9 { 10 Cn, 11 En 12 } 13 14 public static class CultureConfigurer 15 { 16 private static Dictionary<string, string> _enDictionary; 17 private static Dictionary<string, string> _cnDictionary; 18 19 public static void Init() 20 { 21 var assembly = Assembly.Load(new AssemblyName("Localization")); 22 23 var resourceNames = assembly.GetManifestResourceNames(); 24 foreach (var resourceName in resourceNames) 25 { 26 if (resourceName.EndsWith("en-US.json") || resourceName.EndsWith("zh-CN.json")) 27 { 28 using (var stream = assembly.GetManifestResourceStream(resourceName)) 29 { 30 if (stream != null) 31 { 32 using (StreamReader reader = new StreamReader(stream)) 33 { 34 var content = reader.ReadToEnd(); 35 Dictionary<string, string> localizationDictionary = 36 JsonConvert.DeserializeObject<Dictionary<string, string>>(content); 37 if (resourceName.EndsWith("en-US.json")) 38 { 39 _enDictionary = localizationDictionary; 40 } 41 else 42 { 43 _cnDictionary = localizationDictionary; 44 } 45 } 46 } 47 } 48 } 49 } 50 } 51 52 public static string GetValue(string key, Culture culture) 53 { 54 switch (culture) 55 { 56 case (Culture.Cn): 57 { 58 if (_cnDictionary.ContainsKey(key)) 59 { 60 return _cnDictionary[key]; 61 } 62 else 63 { 64 return $"[{key}]"; 65 } 66 } 67 case (Culture.En): 68 { 69 if (_enDictionary.ContainsKey(key)) 70 { 71 return _enDictionary[key]; 72 } 73 else 74 { 75 return $"[{key}]"; 76 } 77 } 78 default: 79 { 80 return $"[{key}]"; 81 } 82 } 83 } 84 } 85 }