Tom Gullen
Tom Gullen

Reputation: 61737

c# sessions "Object reference not set to an instance of an object."

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?

Upvotes: 6

Views: 11599

Answers (2)

Hawxby
Hawxby

Reputation: 2804

ASHX handlers don't have session information by default.

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

IRequiresSessionState 

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1062660

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.

Upvotes: 16

Related Questions