MVC3过滤器实现多语言
如题,以中英文为例。
一、添加Resources文件
1. 创建Global.resx
2.创建Global.en-US.resx
3.向Global.resx和Global.en-US.resx中填入对应的键值
注意:Global.resx 的AccessModifer 要改成Public
二、添加过滤器
1.创建InternationalizationAttribute类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using System.Threading; 7 using System.Globalization; 8 using System.Web.Routing; 9 10 namespace MMSReport.Web.Common 11 { 12 public class InternationalizationAttribute : ActionFilterAttribute 13 { 14 public override void OnActionExecuting(ActionExecutingContext filterContext) 15 { 16 if (filterContext.RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(filterContext.RouteData.Values["lang"].ToString())) 17 { 18 ///从路由数据(url)里设置语言 19 var lang = filterContext.RouteData.Values["lang"].ToString(); 20 Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang); 21 } 22 else 23 { 24 ///从cookie里读取语言设置 25 var cookie = filterContext.HttpContext.Request.Cookies["MvcLocalization.CurrentUICulture"]; 26 var langHeader = string.Empty; 27 if (cookie != null) 28 { 29 ///根据cookie设置语言 30 langHeader = cookie.Value; 31 Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader); 32 } 33 else 34 { 35 ///如果读取cookie失败则设置默认语言 36 langHeader = filterContext.HttpContext.Request.UserLanguages[0]; 37 Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader); 38 } 39 40 ///把语言值设置到路由值里 41 filterContext.RouteData.Values["lang"] = langHeader; 42 } 43 44 /// 把设置保存进cookie 45 HttpCookie _cookie = new HttpCookie("MvcLocalization.CurrentUICulture", Thread.CurrentThread.CurrentUICulture.Name); 46 _cookie.Expires = DateTime.Now.AddYears(1); 47 filterContext.HttpContext.Response.SetCookie(_cookie); 48 } 49 } 50 }
其中使用Cookie记录默认语言
2.文件结构如图
三、设置路由Global.asax
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class MvcApplication : SpringMvcApplication // System.Web.HttpApplication 2 { 3 public static void RegisterGlobalFilters(GlobalFilterCollection filters) 4 { 5 filters.Add(new HandleErrorAttribute()); 6 filters.Add(new InternationalizationAttribute()); 7 } 8 9 public static void RegisterRoutes(RouteCollection routes) 10 { 11 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 12 13 routes.MapRoute( 14 "Globalization", // 路由名称 15 "{lang}/{controller}/{action}/{id}", // 带有参数的 URL 16 new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值 17 new { lang = "^[a-zA-Z]{2}(-[a-zA-Z]{2})?$" } //参数约束 18 ); 19 20 routes.MapRoute( 21 "Default", // Route name 22 "{controller}/{action}/{id}", // URL with parameters 23 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 24 ); 25 26 } 27 28 protected void Application_Start() 29 { 30 log4net.Config.XmlConfigurator.Configure(); 31 32 AreaRegistration.RegisterAllAreas(); 33 34 RegisterGlobalFilters(GlobalFilters.Filters); 35 RegisterRoutes(RouteTable.Routes); 36 } 37 38 }
关键代码:
1. filters.Add(newInternationalizationAttribute());
2.
routes.MapRoute(
"Globalization", // 路由名称
"{lang}/{controller}/{action}/{id}", // 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值
new { lang = "^[a-zA-Z]{2}(-[a-zA-Z]{2})?$" } //参数约束
);
四、页面显示
1.HomeController
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class HomeController : Controller 2 { 3 public ActionResult Index() 4 { 5 return View(); 6 } 7 8 public ActionResult Index2() 9 { 10 return View(); 11 } 12 13 public ActionResult ChangeLanguage(string lang) 14 { 15 return new RedirectResult("Index"); 16 } 17 }
2.Index.cshtml中使用多语言标签替换原来的文字
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <h2>Index</h2> 2 <div> 3 <div> 4 <div> 5 [ @Html.ActionLink("English", "ChangeLanguage", "Home", new { lang = "en-US" }, null) 6 ] [ @Html.ActionLink("中文", "ChangeLanguage", "Home", new { lang = "zh-CN" }, null) 7 ] 8 </div> 9 <div> 10 <span>@MMSReport.Resource.Global.UserName</span> 11 <span>@MMSReport.Resource.Global.UserPwd</span> 12 </div> 13 </div> 14 @Html.ActionLink("Index2","Index2") 15 </div>
3.Index2.cshtml用来做一个简单的跳转测试
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <h2>Index2</h2> 2 3 <h1>@MMSReport.Resource.Global.Index2</h1> 4 5 @Html.ActionLink("Index","Index")
五、运行
结束