我有一个 session 变量,我试图从另一个变量(字符串)中获取值。但是,当我这样做时,如下所示,它不会存储该值。
DataTable table = new DataTable();
MySqlCommand select = new MySqlCommand("SELECT personID, address_addressID from person WHERE email='" + emailAddress + "' and password = '" + passwordR + "'", connect); //brings back the person ID if user details are correct
using (MySqlDataAdapter adapter = new MySqlDataAdapter(select))
{
adapter.Fill(table);
if (table.Rows.Count != 0)
{
string sessionVar = table.Rows[0]["personID"].ToString();
Session["personID"] = sessionVar;
sessionVar 变量是正确的数据,但不会输入到 Session 中,这是不是做错了?
编辑:我已经包含了更多上下文来制作这个 MVCE。
最佳答案
问题总结:
当使用Response.Redirect(URL, true);
分配Session
数据后,你'你会发现它不会被存储。您需要在方法上有一个 return;
并使用 Response.Redirect(URL, false);
。
解释:
可以找到很好的解释 here .这是主要部分的片段:
When you create a new session (that is, the first time you write to a Session variable), ASP.NET sets a volatile cookie on the client that contains the session token. On all subsequent requests, and as long as the server session and the client cookie have not expired, ASP.NET can look at this cookie and find the right session. Now, what Redirect does is to send a special header to the client so that it asks the server for a different page than the one it was waiting for. Server-side, after sending this header, Redirect ends the response. This is a very violent thing to do. Response.End actually stops the execution of the page wherever it is using a ThreadAbortException. What happens really here is that the session token gets lost in the battle.
关于c# - session 变量不存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811462/