我有一个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" })