2
votes

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.

2
When you say "because it was working previously perfect without any issues", the "it was working" part is before wrapping your Settings logic in the Settings class? - Leonel Sanches da Silva
no, I had to start working on a new development in the project, DayPilot Calendar Control, and since then, I have experiencing this problem. - Hennie
@Hennie check my answer and tell me if something is not clear. - mybirthname
@mybirthname, I have tried it, and still same error - Hennie

2 Answers

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

5
votes

Add this Global.asax.cs

using System.Web.SessionState;

protected void Application_PostAuthorizeRequest()
{
    System.Web.HttpContext.Current.
        SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}