Asp.net MVC 多语言应用 – finly – 博客园
- ASP.NET MVC
- 2015-04-30
- 62热度
- 0评论
来源: Asp.net MVC 多语言应用 - finly - 博客园
这里以Mvc3模版项目的登录页为例,简单说一下过程:
首先准备资源文件,即语言包。为web site项目添加Resource文件夹,然后在Resource文件夹下添加两个resx文件
命令行工具ResGen.exe将这两个resx文件生成同名的resources文件,如zh-CN.resources、en-US.resources,生成后将这两个resources文件放到Resource目录下
写一个静态getLang
[code]
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(); } }}[/code]
第二步、为动态切换语言,要在Global.asax文件中添加Application_AcquireRequestState事件,如:
