6

I have an ASHX file:

Object reference not set to an instance of an object.

On the line:

HttpContext.Current.Session["loggedIn"] = true

Is this how I use sessions properly?

Tom Gullen
  • 59,517
  • 82
  • 274
  • 446

2 Answers2

15

I would guess that Session is the culprit here; with reference here, you might want to try adding : IRequiresSessionState to your handler (the code-behind for the ashx). So you should have something like:

public class Handler1 : IHttpHandler, System.Web.SessionState.IRequiresSessionState 
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
        context.Session["loggedIn"] = true;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Note also that it is easier to talk to the context passed in, but HttpContext.Current should work too.

Community
  • 1
  • 1
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
4

ASHX handlers don't have session information by default.

See this page http://www.hanselman.com/blog/GettingSessionStateInHttpHandlersASHXFiles.aspx

IRequiresSessionState 
Hawxby
  • 2,717
  • 19
  • 29