Change culture based on a link MVC4

与世无争的帅哥 提交于 2019-11-30 08:50:34

It's seems I need to override the culture for my resource strings and not the thread. So my final method is this :

    public void ChangeCulture(string lang)
    {
         Resources.Resources.Culture = new CultureInfo(lang);

         Response.Redirect(Request.UrlReferrer.ToString());
    }

Hope this helps.

UPDATE :

The code above is not good when your application is used by multiple users, because it sets same culture for every user, no matter what browser they are using.

The good way to do it is to make a method which sets a cookie in your browser :

    public void ChangeCulture(string lang)
    {
        Response.Cookies.Remove("Language");

        HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["Language"];

        if (languageCookie == null) languageCookie = new HttpCookie("Language");

        languageCookie.Value = lang;

        languageCookie.Expires = DateTime.Now.AddDays(10);

        Response.SetCookie(languageCookie);

        Response.Redirect(Request.UrlReferrer.ToString());
    }

After this ( the tricky way ) you need to make every controller to inherit from one BaseController. It is tricky because you need to override Initialize.

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {


        HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["Language"];
        if (languageCookie != null)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCookie.Value);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageCookie.Value);
        }
        else
        {
        //other code here
        }


        base.Initialize(requestContext);
    }

Remove the line in your web.config:

<globalization uiCulture="auto" culture="auto" />

Setting these to auto will default the language to the user's language set on the browser. This is overriding your Thread setting.

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