2

我有一个类,它通过以下方式创建一个会话:

Session["UserId"] = UserId; // UserId = 1

在 Page_Load 的其中一个页面中,我以这种方式检索会话变量值,效果很好:

if (Session["UserId"] != null){

    var userid = Session["UserId"];
    Welcome.Text = "Hello, " + userid;

}

现在我还需要在我的类中使用会话变量的值。我使用以下方法获取会话值,但它始终返回 null 而会话在我的代码隐藏文件中int useridsession = Convert.ToInt32(HttpContext.Current.Session["UserId"]);正确读取。Session["UserId"];

提到的类:

public static DataTable ManageBookingsDataTable()
{

    int useridsession = Convert.ToInt32(HttpContext.Current.Session["UserId"]);
    SqlConnection con = new SqlConnection(Database.ConnectionString);
    con.Open();
    SqlCommand cmd = new SqlCommand("select bookings.id,user_id, start_date, end_date, pets.name AS 'Pet name' from bookings AS bookings left join users AS usr ON bookings.user_id=usr.id AND bookings.user_id=1 left join pets AS pets ON pets.id=bookings.pet_id WHERE bookings.user_id=@userid_session", con);
    cmd.Parameters.AddWithValue("@userid_session", useridsession);

    SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    string id = string.Empty;
    string name = string.Empty;
    string startdate = string.Empty;
    string enddate = string.Empty;
    string full_string = string.Empty;


    sqlDa.Fill(dt);
    if (dt.Rows.Count > 0)
    {
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            id = dt.Rows[i]["id"].ToString();
            var sdate = dt.Rows[i]["start_date"];
            name = dt.Rows[i]["Pet name"].ToString();
            startdate = dt.Rows[i]["start_date"].ToString();
            enddate = dt.Rows[i]["end_date"].ToString();
            full_string = startdate + " to " + enddate + " (" + name + ")";
            //CurrentBookings.Items.Add(new ListItem(full_string, id));
        }
    }
    return dt;
}

我通过添加来诊断问题HttpContext.Current.Session["UserId"] = 1;,证明当我在同一个类中设置会话时,该方法有效。

我的问题是如何从任何类访问先前创建的会话?

4

1 回答 1

1

无论课程如何,会话都应该可用于会话。为什么不使用同一个类设置和获取会话值?您所有的会议内容都集中在一个地方,因此也更加整洁。

Local.MySession.UserId = UserId;  //Set here
int myUserId = Local.MySession.UserId; //Get here

//Something like this??
namespace Local
{
   //You can add all session variables to this class
   public class MySession
   {
      public static int UserId
      {
         get
         {
            return Convert.ToInt32(HttpContext.Current.Session["userId"] ?? "0");
         }
         set { HttpContext.Current.Session["userId"] = value.ToString(); }
      }

      public static string UserEmail //For Example another session variable
      {
         get { return HttpContext.Current.Session["email"] ?? ""; }
         set { HttpContext.Current.Session["email"] = value; }
      }
   }
}
于 2012-11-23T19:39:58.300 回答