ASP.NET 语言切换

网页中英文版本切换功能实现
1.建立资源文件 web.resx 和web.en-us.resx
2.在web.config中配置默认语言为英文
<appSettings>
  <add key="DefaultCulture" value="en-us"/>
</appSettings>
3.建立Global.asax文件加入代码:
  protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        try
        {
            if (Request.Cookies["CultureResource"] != null)
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Request.Cookies
["CultureResource"].Value);
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo
(ConfigurationSettings.AppSettings["DefaultCulture"].ToString());
                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
            }
            Resources.royo.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
        }
        catch (Exception)
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(ConfigurationSettings.AppSettings
["DefaultCulture"].ToString());
        }
    }
      
 
4.建立语言切换功能类
代码如下
 /// <summary>
    /// 获取语言设置字符串
    /// </summary>
    /// <returns></returns>
    public static string GetCultureString()
    {
        if (Resources.royo.Culture.ToString().ToUpper() == "en-US".ToUpper())
        {
            return "En";
        }
        else
        {
            return "Cn";
        }
    }
    /// <summary>
    /// 更新用户语言设置
    /// </summary>
    /// <param name="culture">用户选择的语言</param>
    public static void UpdateCultureCookie(string culture,int i)
    {
        if (HttpContext.Current.Request.Cookies["CultureResource"] != null)
        {
            HttpContext.Current.Response.Cookies["CultureResource"].Value = culture;
            HttpContext.Current.Response.Cookies["CultureResource"].Expires = System.DateTime.Now.AddDays(30);
        }
        else
        {
            HttpCookie cultureCookie = new HttpCookie("CultureResource");
            cultureCookie.Value = culture;
            cultureCookie.Expires = System.DateTime.Now.AddDays(30);
            HttpContext.Current.Response.Cookies.Add(cultureCookie);
        }
        if (i == 1)
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString());
        }
    }

你可能感兴趣的:(职场,休闲,语言切换)