从客户的httphander类中的aspx页面获取会话

时间:2013-01-09 15:22:15

标签: asp.net httphandler

我在同一个域中有一个aspx页面和自定义httphandler。在aspx页面(test.aspx)中,我使用

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

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

%>

创建会话变量,但是当我想在httphandler中调用变量时

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

当我切换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.

如何从httphandler调用会话?

感谢

更新

将代码更改为

if (context.Session["UserID"] != null)
response.Write(context.Session["UserID"].ToString());
很奇怪,当我使用ip访问网页时,它可以工作。但我使用域名访问页面,它显示空白

2 个答案:

答案 0 :(得分:1)

始终检查会话是否为空。

//Check session variable null or not
if (HttpContext.Current.Session["UserID"] != null)
{
    //Retrieving User ID from Session
}
else
{
 //Do Something else
}

答案 1 :(得分:0)

首先使用context,然后在使用它之前检查它是否为null

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

如果处理程序没有看到会话可能是因为您没有设置更正cookie,并且会话基于cookie。在web.config上的cookies行上设置domain,而不是www.

<httpCookies domain="youdomain.com" httpOnlyCookies="false" requireSSL="false" />
相关问题