title: Getting NullReferenceException and object reference not set to an instance of an object when checking if session is null with ASP.NET 5 and MVC 6
body: <p>I am trying to get session to work in my project but I am getting</p>
  
  <blockquote>
    <p>NullReferenceException</p>
  </blockquote>
  
  <p>and </p>
  
  <blockquote>
    <p>Object reference not set to an instance of an object</p>
  </blockquote>
  
  <p>when checking if a specific session exists using this code:</p>
  
  <pre><code>if (_httpContextAccessor.HttpContext.Session.GetString("CompanyCode") != null)
    {
      queryArgs.CompanyCode = _httpContextAccessor.HttpContext.Session.GetString("CompanyCode").ToString();
    } else { ... }
  </code></pre>
  
  <p>The exception is thrown on the if statement line, which have me guessing the session object must not be initialized correctly, otherwise it would simply move through it.</p>
  
  <p>I have added session to the project with these settings</p>
  
  <p>project.json:</p>
  
  <pre><code>"Microsoft.AspNet.Session": "1.0.0-rc1-final"
  </code></pre>
  
  <p>Startup.cs:</p>
  
  <pre><code>services.AddCaching();
  services.AddSession();
  services.AddTransient&lt;GQFacade&gt;();
  app.UseSession();
  </code></pre>
  
  <p>Finally I have injected it in the class I'm using with: </p>
  
  <pre><code>private static IHttpContextAccessor _httpContextAccessor;
  
  public GQFacade(IHttpContextAccessor httpContextAccessor)
      {
          _httpContextAccessor = httpContextAccessor;
      }
  </code></pre>
  
  <p>I used these guides as sources:</p>
  
  <p><a href="https://neelbhatt40.wordpress.com/2015/09/07/implement-sessions-in-asp-net-5vnext-and-mvc-6/" rel="nofollow noreferrer">https://neelbhatt40.wordpress.com/2015/09/07/implement-sessions-in-asp-net-5vnext-and-mvc-6/</a></p>
  
  <p><a href="http://benjii.me/2015/07/using-sessions-and-httpcontext-in-aspnet5-and-mvc6/" rel="nofollow noreferrer">http://benjii.me/2015/07/using-sessions-and-httpcontext-in-aspnet5-and-mvc6/</a></p>
  
  <p>Any help would be much appreciated!</p>
  
  <p><strong>Edit:</strong> This question has been identified as a possible duplicate to this question: <a href="https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it">What is a NullReferenceException, and how do I fix it?</a></p>
  
  <p>I read that post before i posted this one actually and I decided it was not the same type of question. This is how I reasoned:</p>
  
  <p>That question is about what nullreference exception is, and what I can tell the basic solution to that question is to check whether it is null or not before doing anything with your code. That is exactly what I'm doing. Secondly, my question is about why it throws the nullreference exception when I am CHECKING if there is null. Hence, it is ON the if statement where my problem lies (at least it's there the exception is thrown).</p>