我需要將用戶轉移到需要存儲在不同會話中的會話數據的頁面。我可以將會話數據從一個瀏覽器遷移到另一個嗎? - 網絡開發
在某些情況下是否可以通過在用戶瀏覽器上設置會話cookie來遷移會話數據?
目前我沒有解決方法,使用會話數據似乎是我目前唯一的選擇。
我需要將用戶轉移到需要存儲在不同會話中的會話數據的頁面。我可以將會話數據從一個瀏覽器遷移到另一個嗎? - 網絡開發
在某些情況下是否可以通過在用戶瀏覽器上設置會話cookie來遷移會話數據?
目前我沒有解決方法,使用會話數據似乎是我目前唯一的選擇。
是否有可能在某些情況下 通過用戶的瀏覽器 設置 會話cookie遷移會話數據?
當然可以。只需設置一個新的cookie並重定向。你將不得不做這個服務器端。設置會話cookie客戶端將會產生問題。
const string sessionStateCookieName = "ASP.NET_SessionId";
string sessionId = "some session id";
HttpCookie cookie = new HttpCookie(sessionStateCookieName, sessionId) { Path = "/", HttpOnly = true };
Response.Cookies.Remove(sessionStateCookieName);
Response.Cookies.Add(cookie);
// force a redirect to complete session switch
Response.Redirect(Request.Path);
您可以在此展開。這裏是一個工作示例.aspx頁面。要切換會話,只需添加一個url參數'sessionId'。
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
// this is the method that does the magic
protected override void OnPreInit(EventArgs e)
{
var sessionId = Request["sessionId"];
if (!string.IsNullOrEmpty(sessionId))
{
// this could be found via reflection if different sessionstate cookie name is used in config
const string sessionStateCookieName = "ASP.NET_SessionId";
HttpCookie cookie = new HttpCookie(sessionStateCookieName, sessionId) { Path = "/", HttpOnly = true };
Response.Cookies.Remove(sessionStateCookieName);
Response.Cookies.Add(cookie);
// force a redirect to complete session switch
Response.Redirect(Request.Path);
}
}
// the rest of this script is just demo code
protected void Page_Load(object sender, EventArgs e)
{
CurrentSessionIdLabel.Text = Session.SessionID;
}
protected void SwitchSessionButton_Click(object sender, EventArgs e)
{
// this is the session we wish to switch to
string switchToSessionId = SessionIdTextBox.Text;
Response.Redirect(Request.Path + "?sessionId=" + Server.UrlEncode(switchToSessionId));
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<div>
Current SessionId<br />
<asp:Label ID="CurrentSessionIdLabel" runat="server"></asp:Label>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Desired SessionId"></asp:Label>
<br />
<asp:TextBox ID="SessionIdTextBox" runat="server"></asp:TextBox>
<br />
<asp:Button ID="SwitchSessionButton" runat="server" Text="Switch Session" OnClick="SwitchSessionButton_Click" />
</div>
</form>
</body>
</html>
不,瀏覽器不共享cookie。雖然如果您使用cookieless sessions它將會工作。
如果您有登錄機制,則可以將數據與登錄用戶(在數據庫中?)關聯,而不是將其放入會話中。
@Yuriy:我的意思是改變cookie中的會話ID – RadiantHex 2010-04-05 12:58:54