现在的位置: 主页 > 企业简介 > 文章正文

Asp.net MVC 多语言应用

作者:陕西芙爱尔婚庆礼仪服务有限公司 来源:www.fair521.com 未知发布时间:2017-09-07 12:54:22
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); }

  

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:武汉网站建设 https://www.feimao666.com

上一篇:复习php知识点七 下一篇:最后一页