【问题标题】:Why can't Session variable be accessed outside a method?为什么不能在方法之外访问 Session 变量?
【发布时间】:2014-07-07 11:08:25
【问题描述】:

我是 ASP.NET 的新用户,我试图将每个页面分成变量、事件和方法。我使用几乎在每个方法和事件中都使用的会话变量。因此,我没有从每个方法中提取它并将其存储在变量中,而是尝试在页面级别提取它。但是在变量之外无法识别关键字“会话”。这是为什么?

public partial class OnCall_OnCall_History : System.Web.UI.Page
{
#region Variables
string ID = Convert.ToString(Session["ID"]);  //Not allowed 
#endregion

#region PageLoad
protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
       string ID  = (string)(Session["ID"]); //Allowed
    }
}
#endregion

}

【问题讨论】:

    标签: asp.net web


    【解决方案1】:

    那是因为你在声明中初始化了变量,然后赋值将在构造函数中执行。这发生在设置 Page 对象的属性之前,以便页面知道存在请求和会话。

    Init 事件处理程序中移动这些分配。该事件发生在其他事件之前,但在正确设置 Page 对象之后。

    看起来像这样:

    protected string ID;
    
    protected void Page_Init(object sender, EventArgs e) {
      ID = Convert.ToString(Session["ID"]);
    }
    

    【讨论】:

      【解决方案2】:

      我不知道为什么,但你可以这样使用

      string ID = Convert.ToString(HttpContext.Current.Session["ID"]);
      

      所以你的代码可以是

      public partial class OnCall_OnCall_History : System.Web.UI.Page
      {
      
          string ID = Convert.ToString(HttpContext.Current.Session["ID"]); 
          protected void Page_Load(object sender, EventArgs e)
          {
              if (!IsPostBack)
              {
                    string ID  = (string)(Session["ID"]); //Allowed
               }
          }
      }
      

      这是两者之间的区别
      Difference between Session and HttpContext.Current.Session
      What is the difference between these two HttpContext.Current.Session and Session - asp.net 4.0

      【讨论】:

      • 我刚试过,它说:“对象引用未设置为对象的实例”
      【解决方案3】:

      Session 对象在 ASP.NET 页面的上下文中可用。需要为 asp.net 页面上下文发出请求,因此会话可用。

      Httpplication -> HttpContext -> HttpSession

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多