AI智能
改变未来

ASP.NET MVC 实现中英文切换(全球化)


需求

实现中英文切换,我这里使用的是点击链接。点击中文时:

点击英文时:

view获取当前 url 的

controller

@ViewContext.RouteData.Values[\"controllerName\"]

view获取当前 url 的

Action

@ViewContext.RouteData.Values[\"actionName\"]

准备资源

新建Resourse文件,我这里命名为MyResources.resx,相应的在后面添加语言值(直接复制)可上网查查各种语言对应的代码,中文是

zh-CN

,英文是

en-US


在view里使用资源

@Resources.MyResources.home

@Resources.MyResources

+

key


确保注册路由和过滤器

添加路由

routes.MapRoute(name: \"Localization\", // 路由名称url: \"{lang}/{controller}/{action}/{id}\", // 带有参数的 URLconstraints: new { lang = \"zh-CN|en-US\" }, //限制可输入的语言项defaults: new { lang = \"zh-CN\", controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }//参数默认值);

新建过滤器:(进入系统时会设置默认的lang值)

using System;using System.Collections.Generic;using System.Globalization;using System.Linq;using System.Threading;using System.Web;using System.Web.Mvc;namespace e_form.filter{public class LocalizationAttribute : ActionFilterAttribute{public override void OnActionExecuting(ActionExecutingContext filterContext){//判断是否为空if (filterContext.RouteData.Values[\"lang\"] != null &&!string.IsNullOrWhiteSpace(filterContext.RouteData.Values[\"lang\"].ToString())){//从路由数据(url)里设置语言var lang = filterContext.RouteData.Values[\"lang\"].ToString();Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);}else{//从cookie里读取语言设置var cookie = filterContext.HttpContext.Request.Cookies[\"Language\"];var langHeader = string.Empty;if (cookie != null){//根据cookie设置语言langHeader = cookie.Value;Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);}else{//如果读取cookie失败则设置默认语言langHeader = filterContext.HttpContext.Request.UserLanguages[0];Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);}//把语言值设置到路由值里filterContext.RouteData.Values[\"lang\"] = langHeader;}/// 把设置保存进cookieHttpCookie _cookie = new HttpCookie(\"Language\", Thread.CurrentThread.CurrentUICulture.Name);_cookie.Expires = DateTime.Now.AddYears(1);filterContext.HttpContext.Response.SetCookie(_cookie);base.OnActionExecuting(filterContext);}}}

添加过滤器

设置链接切换语言

替换资源

把需要转换的文本替换为资源。

<ul class=\"navbar-nav mr-auto mt-2 mt-lg-0\"><li class=\"nav-item\">@Html.ActionLink(Resources.MyResources.home, \"Index\", \"Home\", new { @class = \"nav-link activelink\" })</li><li class=\"nav-item\">@Html.ActionLink(Resources.MyResources.Team, \"Team\", \"Home\", new { @class = \"nav-link\" })</li><li class=\"nav-item\">@Html.ActionLink(Resources.MyResources.Design, \"Design\", \"Home\",new { @class = \"nav-link\" })</li><li class=\"nav-item\">@Html.ActionLink(Resources.MyResources.Admin, \"HAAH\", \"Home\", new { @class = \"nav-link\" })</li><li class=\"nav-item\">@Html.ActionLink(Resources.MyResources.Search, \"Search\", \"Home\", new { @class = \"nav-link\" })</li></ul>

以上。

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » ASP.NET MVC 实现中英文切换(全球化)