实际上我正在尝试将数据从.aspx发送到.ashx文件。我在.aspx中使用会话并尝试在 .ashx 中获取会话的值,但它显示异常::对象引用未设置为对象的实例。
这是我的代码:-
.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";
}
}
这里显示会话="你好印度"
我的问题:-
有没有办法将数据从.aspx发送到.ashx文件?
我检查了这么多链接,所有链接都使用 if 为 null,但我已经签入.aspx文件,它在那里显示值,但在 .ashx 文件中显示 null 为什么??(对于特殊情况,我们可以使用/写入if条件,但我已经检查了字符串会话是否有值。
我错过了什么吗??谢谢
这些是我已经使用过的链接:-
如何访问.ashx文件中的会话?
在 c# 中访问上下文会话变量
在 aspx 中添加Session["MId"]
.在灰烬中,您正在阅读Session["MailId"]
.
使你正在使用的密钥相同。(即MId
或MailId
,但不能两者兼而有之)。
建议你定义一个常量来定义这个值,因为它是共享的,那么你可以避免这样的问题。
现在它正在工作。我做了这些更改:-
而不是
[WebMethod(enableSession:true)]
我把
[WebMethod(EnableSession = true)]
但两者都是正确的方法。
我包括 async: false
在我的阿贾克斯电话中。(我认为在设置会话之前,它正在尝试阅读它)
这段代码对我很好用
protected void Button1_Click(object sender, EventArgs e)
{
Session["MailId"] = "somemail@address.com";
Response.Redirect("Handler.ashx");
}
///在 ashx 中编码
public class Handler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
string sessionValue = context.Session["MailId"].ToString();
context.Response.Write(sessionValue);
}
public bool IsReusable {
get {
return false;
}
}
}
我想知道你是否从 ajax 调用访问处理程序