HttpContext.Current.Session - NullReferenceException

14,387

Solution 1

        public static Settings Current
        {
            get
            {
                if(HttpContext.Current.Session == null)
                {
                     Settings s = new Settings();
                     return s;
                }
                if (HttpContext.Current.Session["Settings"] == null)
                {
                    Settings s = new Settings();
                    HttpContext.Current.Session["Settings"] = s;
                    return s;
                }

                return (Settings)HttpContext.Current.Session["Settings"];
            }
        }

You are wrapping the Session["Settings"] to Setting class when it is null. If you change the code like this it should work.

Learn to use debug in the future, you will resolve errors like this really fast !

Solution 2

Add this Global.asax.cs

using System.Web.SessionState;

protected void Application_PostAuthorizeRequest()
{
    System.Web.HttpContext.Current.
        SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
Share:
14,387
Hennie Francis
Author by

Hennie Francis

Updated on June 14, 2022

Comments