Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC session is null. Session Variables are not being set

I have the following code in my Global.asax

protected void Application_AcquireRequestState(object sender, EventArgs e)
{           
    if (HttpContext.Current.Handler is IRequiresSessionState)
    {
        if (Request.IsAuthenticated)
        {
            if (HttpContext.Current.Session[this.MemberShipProvider.PrincipalSessionKey] != null)
            {
                CxPrincipal principal;
                try
                {
                    principal = (CxPrincipal)HttpContext.Current.Session[this.MemberShipProvider.PrincipalSessionKey];
                }
                catch
                {
                    principal = null;
                }

                HttpContext.Current.User = principal;
                Thread.CurrentPrincipal = principal;
            }
            else
            { 
                var identity = new CxIdentity("admin", 1, "", true);
                CxPrincipal principalLogin = new CxPrincipal(identity, 1);
                HttpContext.Current.Session[this.MemberShipProvider.PrincipalSessionKey] = principalLogin;
                HttpContext.Current.Session[SessionName.CurrentUser] = "Admin User";
                HttpContext.Current.User = principalLogin;
                Thread.CurrentPrincipal = principalLogin;
                this.FormServiceProvider.SignIn("admin", false); // this is equal to FormsAuthentication.SetAuthCookie

            }
        }
    }
}

The problem is that everytime the Session is object is null. Not only here, I can't use sessions in my application as well. Either the session is being Reset or something like that.

My application doesn't require the user to Login anymore. Therefore I am not using Session.Clear or Session.Abandon any where in my application.

Please help me, why is my session variable not setting?

like image 384
progrAmmar Avatar asked Jan 13 '15 12:01

progrAmmar


1 Answers

You need to implement (and m.b. leave empty) 2 methods in your global.asax.cs:

    void Session_Start(object sender, EventArgs e)
    {
    }

    void Session_End(object sender, EventArgs e)
    {

    }
like image 146
Sergio Avatar answered Nov 12 '22 05:11

Sergio