C# 在c语言中访问上下文会话变量#

C# 在c语言中访问上下文会话变量#,c#,session,ihttphandler,ihttpmodule,C#,Session,Ihttphandler,Ihttpmodule,我有一个ASP.NET应用程序和扩展IHttpModule的dll。我已经使用下面的方法在httpcontext中通过 public class Handler : IHttpModule,IRequiresSessionState { public void Init(HttpApplication httpApp) { httpApp.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute)

我有一个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();

它执行得很好,并从会话中检索到了值。

在这两部分中都使用
System.Web.HttpContext.Current.session[“myvariable”]
为什么需要使用上下文而不是直接使用会话?从代码中,我只能假设您将在会话中设置一个值,然后在页面加载时读取该值。您可以这样做,而不是像这样做:

  • 添加一个全局应用程序类,右键单击项目,添加>新建项,选择全局应用程序类,然后在该文件上插入以下代码以初始化该值

    protected void Session_Start(object sender, EventArgs e)
    {
        Session["myvariable"] = "Gowtham";
    }
    
  • 在加载页面上,您可以通过以下方式访问:

    if ( Session["myvariable"] != null ) {
        String token = Context.Session["myvariable"].ToString();
    }
    

  • 希望这对您有所帮助。

    不必使用全局应用程序类,也可以实现