【发布时间】:2026-01-12 18:35:10
【问题描述】:
实际上我正在尝试将数据从 .aspx 发送到 .ashx 文件。我在 .aspx 中使用 Session 并试图在 .ashx 中获取 session 的值,但它显示异常:: Object reference not set to an instance of an object.
这是我的代码:-
.aspx 代码
[WebMethod(enableSession:true)]
public static string SetId(string Id)
{
HttpContext.Current.Session["MId"] = Id.ToString(); Console.Write(" ");
string session = HttpContext.Current.Session["MId"].ToString(); // Here I am getting value
//string session = HttpContext.Current.Session["MId"].ToString();
//BatchReadEmails.EmailProperties session = new BatchReadEmails.EmailProperties();
//session.MailId = Id.ToString();
return "Ok";
}
我在字符串会话中获得了价值。
.ashx 代码:-
public class ChangeLogHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string session = "";
if (context.Session["MId"] != null)
session = context.Session["MId"].ToString();
else
session = "Hello India";
}
}
这里显示 session = "Hello India"
我的问题:-
有没有办法将数据从 .aspx 发送到 .ashx 文件?
我检查了这么多链接都在使用 if for null 但我已经在 .aspx 文件中检查它在那里显示值但在 .ashx 文件中显示 null 为什么? (对于特殊情况,我们可以使用/编写 if 条件,但我已经检查过字符串会话是否有价值。
我错过了什么吗?谢谢
这些是我已经使用的链接:-
How to access Session in .ashx file?
Accessing context session variables in c#
【问题讨论】:
-
我注意到您在页面中使用 web 方法来设置会话值。如果您将会话值设置为主 Page_Load 中的某个值,它会起作用吗?
-
是的,它来了,如果我在Page_Load中定义
-
你确定 webmethod 是在调用 ashx 之前执行的吗?
-
是的,它被执行了。并且正在使用“会话”变量来检查它是否包含某些内容。
-
您能否更新 ashx 代码 - 显示的代码无法编译(因为代码只是在类主体中)。请参阅我对 SSCCE 的评论 - 如果您需要建设性的帮助并且人们不会感到沮丧,这很重要。