创业项目中涉及到多语言切换的需求,对比了一些关于ASP.Net下多语言的解决方案通常分为如下三种方式:javascript
1.数据库方式 - 创建相应的语言表,能够从后台配置语言数据。java
2.XML方式 - 不一样的语言配置不一样的xml文件,比较灵活可是xml比较厚重。数据库
3.Resources 感受不够灵活,技术操做容易些,要是其余人搭配就比较麻烦。后端
以上三种方式网上有不少介绍,不作过多探讨。缓存
个人方式是结合js文件来统一先后端语言配置,并更容易让技术和翻译进行搭配工做。this
创建语言文件,能够任意添加语言文件。翻译
zh_CN.js文件内容:code
var lan = { "Size": "大小", "Close": "关闭" };
ru.js文件内容:xml
var lan = { "Size":"Размер", "Close":"Закрыть" };
前台js使用方式blog
<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")
欢迎有多语言开发经验的进行交流。