2010-04-05 65 views

回答

1

是否有可能在某些情況下 通過用戶的瀏覽器 設置 會話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> 
0

不,瀏覽器不共享cookie。雖然如果您使用cookieless sessions它將會工作。

+0

@Yuriy:我的意思是改變cookie中的會話ID – RadiantHex 2010-04-05 12:58:54

0

如果您有登錄機制,則可以將數據與登錄用戶(在數據庫中?)關聯,而不是將其放入會話中。

相關問題