多语言IhttpModule方式

来源:互联网 发布:编程算法书籍知乎 编辑:程序博客网 时间:2024/05/18 02:24

public class MatchLanguage
{
    private static Dictionary<string, int> _dicLang;
    public MatchLanguage()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    private static string GetLanguage()
    {
        if (HttpContext.Current.Cache["MatchLanguage_dicLang"] != null)
        {
            _dicLang = HttpContext.Current.Cache["MatchLanguage_dicLang"] as Dictionary<string, int>;
        }
        else
        {
            _dicLang = new Dictionary<string, int>();
            _dicLang.Add("zh-cn", 1);
            _dicLang.Add("en-us", 2);
            HttpContext.Current.Cache.Insert("MatchLanguage_dicLang", _dicLang, null, DateTime.Now.AddDays(1),System.Web.Caching.Cache.NoSlidingExpiration);
        }
        string lang="zh-cn";
        if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["lang"]))
        {
            if (_dicLang.ContainsKey(HttpContext.Current.Request.QueryString["lang"].ToLower()))
            {
                lang = HttpContext.Current.Request.QueryString["lang"].ToLower();
            }
        }
        return lang;
    }

    public static void SetLanguage()
    {

        System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(GetLanguage());
      
    }

public class InfoHttpModule : IHttpModule
{
 public static string GetCommon(string key)
        {
            string result = Resources.Common.ResourceManager.GetString(key);
            return result;
        }


  public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(Begin_Request);
            context.EndRequest += new EventHandler(End_Request);
        }
 private void Begin_Request(Object sender, EventArgs e)
        {
            startTime = DateTime.Now;
            MatchLanguage.SetLanguage();
        }
}

程序就会根据当前的 CurrentUICulture  去找对应的资源文件
<httpModules>
      <add type="Sunxw.SEO.InfoHttpModule" name="InfoHttpModule"/>
<htpModules>

原创粉丝点击