.net mvc 国际化
1、创建资源文件(culture区分很重要,格式不能写错,不区分大小写)
2、设置路由
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); var cultureRoute = routes.MapRoute("Culture", "{culture}/{controller}/{action}/{id}", new { culture = "zh-CN", controller = "Home", action = "Index", area = "", id = UrlParameter.Optional }, new CulturePrefixRule(), //指定URL参数值的规则 new[] { "Seven.MainUI.Controllers" });//指定要映射的命名空间 cultureRoute.Constraints = new RouteValueDictionary(); cultureRoute.Constraints.Add("culture", new CulturePrefixRule()); // routes.MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "Home", action = "Index"} ); } } public class CulturePrefixRule : IRouteConstraint { //获取支持的区域型列表 IEnumerable<string> cultureConllection = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(p => p.Name.ToLower()); /// <summary> /// /// </summary> /// <param name="httpContext">封装有关 HTTP 请求的信息</param> /// <param name="route">此约束所属的对象</param> /// <param name="parameterName">正在检查的参数的名称。</param> /// <param name="values">一个包含 URL 的参数的对象</param> /// <param name="routeDirection">一个对象,指示在处理传入请求或生成 URL 时,是否正在执行约束检查。</param> /// <returns></returns> public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var routeValue = (string)values[parameterName]; if (string.Equals(routeValue, "zh-hans-cn", StringComparison.OrdinalIgnoreCase)) { values[parameterName] = "zh-cn"; } return cultureConllection.Contains(values[parameterName].ToString().ToLower()); } }
3、在用户请求当前状态时触发事件(Global)
protected void Application_AcquireRequestState(object sender, EventArgs e) { RouteCollection cons = RouteTable.Routes; //国际化设置 if (HttpContext.Current.Session != null) { var cultureInfo = (CultureInfo)Session["Culture"];//本地化语言 // 判断Session中是否有值,没有就设置默认值 if (cultureInfo == null) { string langName = "zh-CN"; if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0) { langName = HttpContext.Current.Request.UserLanguages[0]; } if (string.Equals(langName, "zh-hans-cn", StringComparison.OrdinalIgnoreCase)) { langName = "zh-cn"; } cultureInfo = new CultureInfo(langName); Session["Culture"] = cultureInfo; } Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name); } }
4、在页面跳转前改变页面请求的地址,BaseController : Controller 其他页面继承BaseController页面
/// <summary> /// 对调用构造函数时可能不可用的数据进行初始化 /// </summary> /// <param name="requestContext"></param> protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); //获取路由的culture值 object cultureValue; //检测ci参数 if (requestContext.RouteData.Values.TryGetValue("culture", out cultureValue)) { CultureInfo culture = CultureProvider.GetCultureInfo(cultureValue.ToString()); try { if (culture == null) { culture = CultureProvider.GetCultureInfo(defaultLanguage); } Thread.CurrentThread.CurrentUICulture = CultureProvider.GetCultureInfo(cultureValue.ToString()); Thread.CurrentThread.CurrentCulture = CultureProvider.GetCultureInfo(cultureValue.ToString()); Response.Cookies.Add(new HttpCookie(CultureProvider.culturecookiekey, culture.Name)); } catch (Exception) { throw new Exception("Culture Error!"); } } else { Thread.CurrentThread.CurrentUICulture = CultureProvider.GetCultureInfo(defaultLanguage); Thread.CurrentThread.CurrentCulture = CultureProvider.GetCultureInfo(defaultLanguage); requestContext.HttpContext.Response.Cookies.Add(new HttpCookie(CultureProvider.culturecookiekey, defaultLanguage)); //HttpCookie cLang = requestContext.HttpContext.Request.Cookies[CultureProvider.culturecookiekey]; //if (cLang != null) { // cultureValue = cLang.Value; //} //else //{ // string[] langs = requestContext.HttpContext.Request.UserLanguages; // if(langs != null && langs.Length > 0) // { // cultureValue = langs[0].Split(';').First(); // } //} //if (cultureValue == null) //{ // cultureValue = CultureProvider.culturedefault; //} //redirectUrl = string.Format(@"/{0}{1}", // cultureValue.ToString(), // requestContext.HttpContext.Request.RawUrl); } } //protected override IActionInvoker CreateActionInvoker() //{ // return new CustomControllerActionInvoker(redirectUrl); //} public static class CultureProvider { public const string culturecookiekey = "Lang"; //默认 public const string culturedefault = "zh-CN"; public static CultureInfo GetCultureInfo(string ci) { try { return new CultureInfo(ci); } catch { return null; } } }
5、效果
注:次借鉴P_Chou