0

I am in the process of upgrading a project to a newer version of Visual Studio, .Net Framework and our masterpage for the application. Unfortunately, when doing this, some of the code no longer works.

On my default.aspx.cs page, I am setting a session variable: Session["user"] = sUser;

I need to access this session variable in a security.cs file (not a code-behind). Unfortunately, every time I try to access this: string sUser = HttpContext.Current.Session["user"].ToString();

I am getting a "'HttpContext.Current.Session["user"]' threw an exception of type 'System.NullReferenceException'" error.

I understand that by design, a class file doesn't have access to Session, but I am hoping there is some way I can access this to save me a lot of work. If I cannot access Session, I will need to change a lot of code to pass around the user into a bunch of class files. If I can somehow use session (or some other method to set in the page_load of the default.aspx.cs file), the change will be very minor.

Is there someway to make this work?

  • 1
    Is `HttpContext` `null`? Or is it `HttpContext.Current`? Or is it `HttpContext.Session`? – mjwills May 24 '18 at 13:19
  • 1
    Is the `Security.cs` code being executed in the context of a web request? Or perhaps from a new thread or task? – mjwills May 24 '18 at 13:20
  • It would be awesome if you could provide a [mcve]. – mjwills May 24 '18 at 13:20
  • HttpContext.Current *does* work, where the class is participating in a current request. In your example, you are doing the ToString() of an object of a session of a http context all in one line. To help see what is going on, split that out into four lines (get your current context, then get your session of it, then get your "user" object from the session, then do your ToString() of that). That may give you the clues as to where this is not doing what you expect. – Jinlye May 24 '18 at 13:43
  • Thanks guys for the help. I see what you mean as to the "context" of the request. The security.cs file is being called from a handler (*.ashx) file. HttpContext.Current.Session is null. Is there a way to get the session from inside a handler? –  May 24 '18 at 14:52
  • 1
    Possible duplicate of [How to access Session in .ashx file?](https://stackoverflow.com/questions/11447196/how-to-access-session-in-ashx-file) – bfontaine May 24 '18 at 14:58

1 Answers1

0

Thanks all for the help. You helped me track down the answer. Here is the solution I needed:

How to access Session in .ashx file?