我有一个以下列方式创建会话的类:
Session["UserId"] = UserId; // UserId = 1
在Page_Load的其中一个页面中,我以这种方式检索会话变量值,这样可以正常工作:
if (Session["UserId"] != null){
var userid = Session["UserId"];
Welcome.Text = "Hello, " + userid;
}
现在我还需要在我的类中使用会话变量的值。我使用以下方法获取会话值int useridsession = Convert.ToInt32(HttpContext.Current.Session["UserId"]);
但它始终返回null,而在我的代码隐藏文件中使用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;
来诊断问题,这证明了当我在同一个类中设置会话时,该方法可以正常工作。
我的问题是如何从任何类访问以前创建的会话?
答案 0 :(得分: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; }
}
}
}