創業項目中涉及到多語言切換的需求,對比了一些關於ASP.Net下多語言的解決方案一般分為以下三種方式:
1.數據庫方式 - 建立相應的語言表,可以從后台配置語言數據。
2.XML方式 - 不同的語言配置不同的xml文件,比較靈活但是xml比較厚重。
3.Resources 感覺不夠靈活,技術操作容易些,要是其他人搭配就比較麻煩。
以上三種方式網上有很多介紹,不做過多探討。
我的方式是結合js文件來統一前后端語言配置,並更容易讓技術和翻譯進行搭配工作。
建立語言文件,可以任意添加語言文件。
zh_CN.js文件內容:
var lan = { "Size": "大小", "Close": "關閉" };
ru.js文件內容:
var lan = { "Size":"Размер", "Close":"Закрыть" };
前台js使用方式
<script type="text/javascript" src="/i18n/ru.js"></script> //語言文件可以根據后台參數動態切換 <script type="text/javascript"> $(function () { alert(lan.Close); }); </script>
后台讀取js文件並解析到Hashtable
public static class Localization { /// <summary> /// 加載語言文件 /// </summary> /// <param name="code">語言code</param> /// <returns></returns> public static Hashtable Loadi18n(string code) { if (string.IsNullOrEmpty(code)) { throw new ArgumentNullException("語言代碼為空..."); } string filePath = HttpContext.Current.Server.MapPath("~/i18n/" + code + ".js"); if (!File.Exists(filePath)) { throw new FileNotFoundException("語言文件不存在..."); } string cacheName = "cache_lan_" + code; Hashtable i18nHashtable = new Hashtable(); if (HttpRuntime.Cache[cacheName] != null) { i18nHashtable = HttpRuntime.Cache[cacheName] as Hashtable; } else { string lanText = ""; //獲取文件內容 using (StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8)) { lanText = reader.ReadToEnd(); } //去掉干擾字符 lanText = Regex.Replace(lanText, "[\f\n\r\t\v]", ""); //匹配文本內容 Regex regex = new Regex(@"\{.*\}", RegexOptions.IgnoreCase | RegexOptions.Multiline); Match match = regex.Match(lanText); i18nHashtable = JsonConvert.DeserializeObject<Hashtable>(match.Value); //緩存信息 CacheDependency fileDepends = new CacheDependency(filePath); HttpRuntime.Cache.Insert(cacheName, i18nHashtable, fileDepends); } return i18nHashtable; } /// <summary> /// 獲取語言值 /// </summary> /// <param name="code">語言code</param> /// <param name="key">語言key</param> /// <returns></returns> public static string M(string code, string key) { Hashtable i18nHashtable = Loadi18n(code); if (i18nHashtable.ContainsKey(key)) { return i18nHashtable[key].ToString(); } return string.Empty; } /// <summary> /// 獲取語言值 /// </summary> /// <param name="i18nHashtable">語言集合</param> /// <param name="key">語言key</param> /// <returns></returns> public static string M(this Hashtable i18nHashtable, string key) { if (i18nHashtable.ContainsKey(key)) { return i18nHashtable[key].ToString(); } return string.Empty; } }
調用方式:
//語言部分可以根據參數自由切換 Localization.M("ru", "Size") //如果頁面中調用多次可以使用如下方式 Hashtable lan = Localization.Loadi18n("ru"); lan.M("Size") lan.M("Close")
歡迎有多語言開發經驗的進行交流。