-1

我在同一个域中有一个 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 访问网页时,它可以工作。但是我使用域名访问页面,它显示为空白

4

2 回答 2

1

始终检查会话是否为空。

//Check session variable null or not
if (HttpContext.Current.Session["UserID"] != null)
{
    //Retrieving User ID from Session
}
else
{
 //Do Something else
}
于 2013-01-09T15:30:47.940 回答
0

首先使用context第二个检查它是否为空,然后再使用它

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

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

<httpCookies domain="youdomain.com" httpOnlyCookies="false" requireSSL="false" />
于 2013-01-09T15:30:26.143 回答