-1

i have a aspx page and custom httphandler in same domain. In the aspx page (test.aspx), i use

<%@ Page Language="C#" %>
<%

    HttpContext.Current.Session["UserID"] = "ABC";

%>

to create a session variable, but when i want to call the variable in httphandler

public class JpgHttpHandler : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
         response.Write(HttpContext.Current.Session["UserID"].ToString());
    }
}

there is a error message when i toggle the httphandler:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

how can i call the session from httphandler?

thanks

Update

changed the code to

if (context.Session["UserID"] != null)
response.Write(context.Session["UserID"].ToString());

it is strange, when i use ip to access the webpage, it works. But i use the domain name access the page, it displays blank

hkguile
  • 4,235
  • 17
  • 68
  • 139

2 Answers2

1

Always check session is null or not.

//Check session variable null or not
if (HttpContext.Current.Session["UserID"] != null)
{
    //Retrieving User ID from Session
}
else
{
 //Do Something else
}
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
0

First use the context and second check if its null before use it

public class JpgHttpHandler : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
         if(context.Session["UserID"] != null)
             response.Write(context.Session["UserID"].ToString());
    }
}

If the handler did not see the session is probably because you do not have setup correct the cookie, and the session is base on the cookie. Set the domain on the cookies line on web.config, with out the www. as:

<httpCookies domain="youdomain.com" httpOnlyCookies="false" requireSSL="false" />
Aristos
  • 66,005
  • 16
  • 114
  • 150