MVC4多语言支持

第一步 建立资源文件

为WEB项目添加Resource文件夹,然后在Resource文件夹下添加两个resx文件en-US.resx和zh-CN.resx文件。

使用Resgen.exe将resx转为resource文件(Resgen.exe可以放到windows/system32或windows/syswow64下),cmd运行下列语句:

resgen D:\WORKSPACE\Locale\Locale\Resource\en-US.resx D:\WORKSPACE\Locale\Locale\Resource\en-US.resources
resgen D:\WORKSPACE\Locale\Locale\Resource\zh-CN.resx D:\WORKSPACE\Locale\Locale\Resource\zh-CN.resources

将resource文件拷贝至Resource文件夹,删除resx文件。如:

 

第二步 GetLang

写一个静态的GetLang方法,以便服务器端代码使用,然后写一个HtmlHelper扩展方法,以便在前端代码view或js中使用,如:

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Resources; using System.Web; using System.Web.Mvc; namespace Locale.Models { 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; } } }

 

第三步 动态切换语言支持

为动态切换语言,要在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("zh-CN"); this.Session["CurrentLanguage"] = ci; } System.Threading.Thread.CurrentThread.CurrentUICulture = ci; System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(ci.Name); } }

 

第四步 在HomeController中添加ChangeLanguage方法,很简单、就一句代码,如:

public void ChangeLanguage() { Session["CurrentLanguage"] = new System.Globalization.CultureInfo(Request["language"]); }

最后就是View了

@using Locale.Models @{ ViewBag.Title = Html.Lang("test"); } <h2>@ViewBag.Title</h2>

 

本文参考链接:http://blog.163.com/y_p_xu/blog/static/1708571022012769548643/

你可能感兴趣的:(MVC4多语言支持)