Asp.net MVC 多语言应用
这里以Mvc3模版项目的登录页为例,简单说一下过程:
首先准备资源文件,即语言包。为web site项目添加Resource文件夹,然后在Resource文件夹下添加两个resx文件
命令行工具ResGen.exe将这两个resx文件生成同名的resources文件,如zh-CN.resources、en-US.resources,生成后将这两个resources文件放到Resource目录下
写一个静态getLang
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事件,如:
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方法,很简单、就一句代码,如:
public JsonResult ChangeLanguage() { string aa = Request["language"]; Session["CurrentLanguage"] = new System.Globalization.CultureInfo(Request["language"]); return Json("操作成功!", JsonRequestBehavior.AllowGet); }