我有一个 ASP.NET 应用程序和扩展 IHttpModule 的 dll。我已经使用以下方法将会话变量保存在 httpcontext 通过
public class Handler : IHttpModule,IRequiresSessionState
{
public void Init(HttpApplication httpApp)
{
httpApp.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}
public void PreRequestHandlerExecute(object sender, EventArgs e)
{
var context = ((HttpApplication)sender).Context;
context.Session["myvariable"] = "Gowtham";
}
}
在我的 asp.net Default.aspx 页面中,我使用代码来检索值
public partial class _Default : System.Web.UI.Page, IRequiresSessionState
{
protected void Page_Load(object sender, EventArgs e)
{
String token = Context.Session["myvariable"].ToString();
}
}
我收到错误响应
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.
为了确保变量是否存储在会话中,我在将会话中的值存储为之后,通过类处理程序中的以下方法进行了交叉检查
string ss = context.Session["myvariable"].ToString();
它执行得很好并从会话中检索了值。