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

时间:2014-09-23 14:09:53

标签: c# cookies

我正在尝试设置一个Cookie,以便在用户点击切换按钮时更改我网站的文化和文化。这就是我所拥有的:

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不会更新..

任何想法?


谢谢!

1 个答案:

答案 0 :(得分:0)

如果有人想看我的代码,根据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);
        }

    }