asp.net-mvc-3 – ASP.NET MVC语言更改链接
发布时间:2020-12-15 20:14:10 所属栏目:asp.Net 来源:网络整理
导读:我有一个ASP.NET MVC网站,它使用两种语言使用资源.要让服务器以适当的语言呈现站点(取决于用户浏览器中配置的站点),我将以下内容放在我的web.config中: globalization culture="es-es" uiCulture="auto" / 如何添加链接来更改uiCulture?我想将选择存储在co
我有一个ASP.NET MVC网站,它使用两种语言使用资源.要让服务器以适当的语言呈现站点(取决于用户浏览器中配置的站点),我将以下内容放在我的web.config中:
<globalization culture="es-es" uiCulture="auto" /> 如何添加链接来更改uiCulture?我想将选择存储在cookie中,如果它不存在,则回到浏览器配置…是可能吗? 解决方法
您可以查看
following guide.它使用会话来存储当前的用户语言首选项,但代码可能很容易调整,以便使用cookie.这个想法是你会有一个控制器的动作:
public ActionResult ChangeCulture(string lang,string returnUrl) { var langCookie = new HttpCookie("lang",lang) { HttpOnly = true }; Response.AppendCookie(langCookie); return Redirect(returnUrl); } 然后在Global.asax中,您可以订阅Application_AcquireRequestState事件,以便根据cookie的值设置当前的线程文化: protected void Application_AcquireRequestState(object sender,EventArgs e) { var langCookie = HttpContext.Current.Request.Cookies["lang"]; if (langCookie != null) { var ci = new CultureInfo(langCookie.Value); //Checking first if there is no value in session //and set default language //this can happen for first user's request if (ci == null) { //Sets default culture to english invariant string langName = "en"; //Try to get values from Accept lang HTTP header if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0) { //Gets accepted list langName = HttpContext.Current.Request.UserLanguages[0].Substring(0,2); } langCookie = new HttpCookie("lang",langName) { HttpOnly = true }; HttpContext.Current.Response.AppendCookie(langCookie); } //Finally setting culture for each request Thread.CurrentThread.CurrentUICulture = ci; Thread.CurrentThread.CurrentCulture = ci; //The line below creates issue when using default culture values for other //cultures for ex: NumericSepratore. //Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name); } } 现在这是说使用cookies和会话来存储当前语言不是SEO友好.当我需要一个本地化的应用程序时,我喜欢做什么是使用一个特殊的路由,其中??包含语言: routes.MapRoute( "Default","{lang}/{controller}/{action}/{id}",new { lang = "en-US",controller = "Home",action = "Index",id = UrlParameter.Optional } ); 然后使用该语言对我的所有URL进行前缀.这为不同的语言提供唯一的URL,以便机器人可以正确地索引所有内容.现在剩下的是修改Application_AcquireRequestState方法,以便它使用url的lang标记,并根据其值设置正确的Thread.CurrentThread.CurrentUICulture和Thread.CurrentThread.CurrentCulture. 现在,当你想改变语言的时候,你只需要生成正确的链接: @Html.ActionLink("Page index en fran?ais","index",new { lang = "fr-FR" }) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 实体框架 – 带MVC3的EF4 – 我需要存储库模式吗?
- asp.net-mvc-3 – 为什么我的IgnoreRoute不起作用?
- asp.net-mvc – 自定义ActionLink帮助器,它知道你正在使用哪
- asp.net-mvc-3 – 如何在asp.net MVC剃刀中生成dropdownlis
- asp.net-mvc – Asp.net Mvc 2:存储库,分页和过滤如何?
- asp.net – Visual Studio开发服务器(2010)和NTLM授权
- asp.net – 如何调用我的WCF服务构造函数?
- asp.net – 可以通过移动设备的Web浏览器上传图片吗?
- asp.net – 自上一步以来,进程或线程已更改
- asp.net – 在Response.Redirect之后获取上一页网址
推荐文章
站长推荐
热点阅读