ASP.NET MVC language change link

前端 未结 4 1754
伪装坚强ぢ
伪装坚强ぢ 2020-12-24 05:12

I have an ASP.NET MVC site that it\'s in two languages using Resources. To allow the server to present the site in the apropiate language (depending on the one that\'s confi

4条回答
  •  抹茶落季
    2020-12-24 05:50

    An alternative and I feel it is more flexible

     protected override void ExecuteCore()
        {
            if (RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(RouteData.Values["lang"].ToString()))
            {
                SetCulture(RouteData.Values["lang"].ToString());
            }
            else
            {
                var cookie = HttpContext.Request.Cookies["myappculture"];
                if (cookie != null)
                { SetCulture(cookie.Value); }
                else
                { SetCulture(HttpContext.Request.UserLanguages[0]);}
            }
            base.ExecuteCore();
        }
    
    public ActionResult ChangeCulture(string lang, string returnUrl)
        {
    
            SetCulture(lang);
            // Little house keeping
            Regex re = new Regex("^/\\w{2,3}(-\\w{2})?");
            returnUrl = re.Replace(returnUrl,"/" + lang.ToLower());
            return Redirect(returnUrl);
        }
    
    private void SetCulture(string lang)
        {
            CultureInfo ci = new CultureInfo(lang);
            System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
    
            // Force a valid culture in the URL
            RouteData.Values["lang"] = lang;
    
            // save the location into cookie
            HttpCookie _cookie = new HttpCookie("myappculture", Thread.CurrentThread.CurrentUICulture.Name);
            _cookie.Expires = DateTime.Now.AddYears(1);
            HttpContext.Response.SetCookie(_cookie);
        }
    

    In the view

    Multilingual setup in view

    I kept the resource in a different project as follows

    Resources in a different project and Its usage

提交回复
热议问题