這裏以Mvc3模版項目的登陸頁爲例,簡單說一下過程:html
首先準備資源文件,即語言包。爲web site項目添加Resource文件夾,而後在Resource文件夾下添加兩個resx文件web
命令行工具ResGen.exe將這兩個resx文件生成同名的resources文件,如zh-CN.resources、en-US.resources,生成後將這兩個resources文件放到Resource目錄下工具
寫一個靜態getLangui
namespace System.Web.Mvc { using System.Collections; using System.Resources; using System.Linq; public static class LocalizationHelper { public static string Lang(this HtmlHelper html, string key) { return GetLang(key); } public static string GetLang(string key) { var filePath = HttpContext.Current.Server.MapPath("~/Resource"); string language = HttpContext.Current.Session["CurrentLanguage"] == null ? "zh-CN" : HttpContext.Current.Session["CurrentLanguage"].ToString(); string resxPath = string.Format(@"{0}\{1}.resources", filePath, language); ResourceReader reader = new ResourceReader(resxPath); var entry = reader.Cast<DictionaryEntry>().FirstOrDefault<DictionaryEntry>(x => x.Key.ToString() == key); reader.Close(); return entry.Value == null ? "" : (string)entry.Value; } public static string GetLanguage(this HtmlHelper html) { return HttpContext.Current.Session["CurrentLanguage"].ToString(); } } }
第二步、爲動態切換語言,要在Global.asax文件中添加Application_AcquireRequestState事件,如:this
protected void Application_AcquireRequestState(object sender, EventArgs e) { if (HttpContext.Current.Session != null) { System.Globalization.CultureInfo ci = (System.Globalization.CultureInfo)this.Session["CurrentLanguage"]; if (ci == null) { ci = new System.Globalization.CultureInfo(Request.UserLanguages[0].ToString()); this.Session["CurrentLanguage"] = ci; } System.Threading.Thread.CurrentThread.CurrentUICulture = ci; System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(ci.Name); } }
第三步、在HomeController中添加ChangeLanguage方法,很簡單、就一句代碼,如:spa
public JsonResult ChangeLanguage() { string aa = Request["language"]; Session["CurrentLanguage"] = new System.Globalization.CultureInfo(Request["language"]); return Json("操做成功!", JsonRequestBehavior.AllowGet); }