How to change site language using Resources and CultureInfo in ASP .NET MVC?

拈花ヽ惹草 提交于 2021-02-06 13:51:17

问题


I have several resource files for each language I want to support, named like below:

NavigationMenu.en-US.resx
NavigationMenu.ru-RU.resx
NavigationMenu.uk-UA.resx

Files are located in MySolution/Resources/NavigationMenu folder.

I have action which sets CurrentCulture and CurrentUICulture like below

public ActionResult SetLanguage(string lang)
{
    try
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
        return Redirect(Request.UrlReferrer.AbsoluteUri);
    }
    catch(Exception)
    {
        return RedirectToAction("Index");
    }
}

lang parameter values are uk-UA, ru-RU or en-US depending on what link in my view was clicked. Also I have web config globalization defined section:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="ru-RU" uiCulture="ru-RU" />

When my application starts I have Russian language as expected but when I try to change my language with SetLanguage action to English I get no language changes in my views. NavigationMenu.SomeProperty is still Russian. What am I missing?


回答1:


You are updating the culture for the current thread only.

Most sites support localization by including this as part of their URL (in all pages). And with MVC, you can implement this approach by processing the culture using an action filter. This answer has a good solution for this.

Aside from this, you would need to implement this by either persisting the culture to the session or a cookie, and then updating the thread's culture on every request, again by implementing an action filter, or during an application event that contains the request context, such as AquireRequestState.




回答2:


Persist your language in e.g cookie in your SetLanguage() and then in the BaseController or ActionFilter (recommended) get the values from cookie and the update the threads accordingly.
if this doesn't make any sense, take a look at the following nice articles;
CodeProject : http://www.codeproject.com/Articles/526827/MVC-Basic-Site-Step-1-Multilingual-Site-Skeleton
And this One :http://afana.me/post/aspnet-mvc-internationalization.aspx
e.g;

// Save culture in a cookie
        HttpCookie cookie = Request.Cookies["_culture"];
        if (cookie != null)
            cookie.Value = culture;   // update cookie value
        else
        {

            cookie = new HttpCookie("_culture");
            cookie.HttpOnly = false; // Not accessible by JS.
            cookie.Value = culture;
            cookie.Expires = DateTime.Now.AddYears(1);
        }
        Response.Cookies.Add(cookie);


来源:https://stackoverflow.com/questions/16879618/how-to-change-site-language-using-resources-and-cultureinfo-in-asp-net-mvc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!