2

I have been experiencing a Object Reference not set to an instance of an object error in my MVC 4 ASP.NET project's Settings class, that gets my Current Session details. Each time I browse a page the variable throws the NullReferenceException, and could not understand why, because it was working previously perfect without any issues.

namespace TracerCRM.Web
{
    public class Settings
    {
        public static Settings Current
        {
            get
            {
                Settings s = HttpContext.Current.Session["Settings"] as Settings;
                if (s == null)
                {
                    s = new Settings();
                    HttpContext.Current.Session["Settings"] = s;
                }

                return s;
            }
        }
    }
}

I have tried the following things that I encountered during my research:

1: "HttpContext.Current.Session" vs Global.asax "this.Session"

2: Rare System.NullReferenceException show up for a HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"] that was previously populated?

3: The Session object is null in ASP.NET MVC 4 webapplication once deployed to IIS 7 (W 2008 R2)

4: Log a user off when ASP.NET MVC Session expires

5: Login Session lost sometimes when redirect to action in asp.net mvc 3

None of the above worked for me.

Community
  • 1
  • 1
Hennie Francis
  • 124
  • 2
  • 2
  • 18

2 Answers2

7
        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 !

mybirthname
  • 17,949
  • 3
  • 31
  • 55
7

Add this Global.asax.cs

using System.Web.SessionState;

protected void Application_PostAuthorizeRequest()
{
    System.Web.HttpContext.Current.
        SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
criss
  • 71
  • 1
  • 1