Set session variable in Application_BeginRequest

前端 未结 3 2093
臣服心动
臣服心动 2020-12-15 02:38

I\'m using ASP.NET MVC and I need to set a session variable at Application_BeginRequest. The problem is that at this point the object HttpContext.Current.

3条回答
  •  我在风中等你
    2020-12-15 03:18

    You can use the session items in Application_BeginRequest this way:

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //Note everything hardcoded, for simplicity!
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("LanguagePref");
    
            if (cookie == null)
                return;
            string language = cookie["LanguagePref"];
    
            if (language.Length<2)
                return;
            language = language.Substring(0, 2).ToLower();   
            HttpContext.Current.Items["__SessionLang"] = language;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
    
        }
    
        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            if (context != null && context.Session != null)
            {
                context.Session["Lang"] = HttpContext.Current.Items["__SessionLang"];
            }
        }
    

提交回复
热议问题