设置语言cookie以在resx页面之间切换

本文关键字:之间 resx 语言 cookie 以在 设置 | 更新日期: 2023-09-27 18:24:07

当用户单击切换按钮时,我正试图设置一个cookie来更改我网站的区域性和ui区域性。这就是我所拥有的:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        HttpCookie cookie = Request.Cookies["CurrentLanguage"];
        if (!IsPostBack && cookie != null && cookie.Value != null)
        {
            if (cookie.Value.IndexOf("en-") >= 0)
            {
               // currently english
                Culture = "fr-CA";
                UICulture = "fr-CA";
            }
            else
            {
            //currently french
            Culture = "en-CA";
            UICulture = "en-CA";
            }
        }
        ...
    }
}

以及

protected void toggle_lang(object sender, DirectEventArgs e)
    {
        if (Culture.ToString() == "English (Canada)")
        {
            HttpCookie cookie = new HttpCookie("CurrentLanguage");
            cookie.Value = "fr-CA";
            Response.SetCookie(cookie);
            Response.Redirect(Request.RawUrl);
        }
        else 
        {
            HttpCookie cookie = new HttpCookie("CurrentLanguage");
            cookie.Value = "en-CA";
            Response.SetCookie(cookie);
            Response.Redirect(Request.RawUrl);
        }
    }

执行切换功能时,页面会刷新,但区域性和cultureui不会更新。。


有什么想法吗?



谢谢!

设置语言cookie以在resx页面之间切换

如果有人想查看我的代码,要根据cookie设置区域性和ui区域性,您需要重写InitializeCulture(),如下所示:

protected override void InitializeCulture()
    {
        HttpCookie cookie = Request.Cookies["CurrentLanguage"];
        if (!IsPostBack && cookie != null && cookie.Value != null)
        {
            if (cookie.Value.ToString() == "en-CA")
            {
               // currently english
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-CA");
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-CA");
                base.InitializeCulture();
            }
            else
            {
               //currently french
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-CA");
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-CA");
                base.InitializeCulture();
            }
        }
    }

为了切换,设置一个新的cookie并刷新,让上面的函数负责设置页面语言,如下所示:

protected void toggle_lang(object sender, DirectEventArgs e)
    {
        if (Culture.ToString() == "English (Canada)")
        {
            HttpCookie cookie = new HttpCookie("CurrentLanguage");
            cookie.Value = "fr-CA";
           Response.SetCookie(cookie);
           Response.Redirect(Request.RawUrl);
        }
        else 
        {
            HttpCookie cookie = new HttpCookie("CurrentLanguage");
            cookie.Value = "en-CA";
            Response.SetCookie(cookie);
            Response.Redirect(Request.RawUrl);
        }
    }