【问题标题】:Accessing context session variables in c#在 C# 中访问上下文会话变量
【发布时间】:2013-03-21 05:57:22
【问题描述】:

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

它很好地执行并从会话中检索了值。

【问题讨论】:

标签: c# session ihttphandler ihttpmodule


【解决方案1】:

为什么需要直接使用 Context 而不是 Session?从代码中我只能假设您要在 Session 中设置一个值,然后在页面加载时读取该值。您可以这样做,而不是这样做:

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

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

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

希望对您有所帮助..

【讨论】:

  • 可以不使用全局应用程序类
【解决方案2】:

在两个部分都使用System.Web.HttpContext.Current.Session["myvariable"]

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多