I am trying to get session to work in my project but I am getting
NullReferenceException
and
Object reference not set to an instance of an object
when checking if a specific session exists using this code:
if (_httpContextAccessor.HttpContext.Session.GetString("CompanyCode") != null)
{
queryArgs.CompanyCode = _httpContextAccessor.HttpContext.Session.GetString("CompanyCode").ToString();
} else { ... }
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.
I have added session to the project with these settings
project.json:
"Microsoft.AspNet.Session": "1.0.0-rc1-final"
Startup.cs:
services.AddCaching();
services.AddSession();
services.AddTransient<GQFacade>();
app.UseSession();
Finally I have injected it in the class I'm using with:
private static IHttpContextAccessor _httpContextAccessor;
public GQFacade(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
I used these guides as sources:
https://neelbhatt40.wordpress.com/2015/09/07/implement-sessions-in-asp-net-5vnext-and-mvc-6/
http://benjii.me/2015/07/using-sessions-and-httpcontext-in-aspnet5-and-mvc6/
Any help would be much appreciated!
Edit: This question has been identified as a possible duplicate to this question: What is a NullReferenceException, and how do I fix it?
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:
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).