简体   繁体   中英

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

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).

Try without GetString in the if condition

if (_httpContextAccessor.HttpContext.Session["CompanyCode"] != null)
  {
    queryArgs.CompanyCode = _httpContextAccessor.HttpContext.Session.GetString("CompanyCode").ToString();
  }

When the session expires the session variable become null
In order to eliminate this error use try and catch

    @try
    {
        if (_httpContextAccessor.HttpContext.Session.GetString("CompanyCode") != null)
        {
            queryArgs.CompanyCode = _httpContextAccessor.HttpContext.Session.GetString("CompanyCode").ToString();
        }
    }
   catch(Exception ex)
   {
        Response.Redirect("controllerName/ActionName");
   }

when the session expires, it will redirect to the action. Make sure the user logout when session expires by redirecting to the logout action

Ok, I solved it. I found this post and the solution worked for me too, so this could be a possible duplicate to that question. Injected HttpContext is always null

What I did was to add this in Startup.cs in the configure method and then it worked fine.

app.ApplicationServices.GetRequiredService<GQFacade>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM