ASP.NET中用戶端Session狀態的儲存
在我們上面的Session模型簡介中,大家可以發現Session狀態應該儲存在兩個地方,分別是用戶端和伺服器端。用戶端只負責儲存相應網站的 SessionID,而其他的Session資訊則儲存在伺服器端。在ASP中,用戶端的SessionID實際是以Cookie的形式儲存的。如果使用者在瀏覽器的設定中選擇了禁用Cookie,那末他也就無法享受Session的便利之處了,甚至造成不能訪問某些網站。為瞭解決以上問題,在 ASP.NET中用戶端的Session資訊儲存方式分為:Cookie和Cookieless兩種。
ASP.NET中,預設狀態下,在用戶端還是使用Cookie儲存Session資訊的。如果我們想在用戶端使用Cookieless的方式儲存Session資訊的方法如下:
找到當前Web應用程式的根目錄,開啟Web.Config檔案,找到如下段落:
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>
這段話中的cookieless="false"改為:cookieless="true",這樣,用戶端的Session資訊就不再使用Cookie儲存了,而是將其通過URL儲存。關閉當前的IE,開啟一個新IE,重新訪問剛才的Web應用程式,就會看到類似下面的樣子:
其中,http://localhost/MyTestApplication/(ulqsek45heu3ic2a5zgdl245)/default.aspx中黑體標出的就是用戶端的Session ID。注意,這段資訊是由IIS自動加上的,不會影響以前正常的串連。
ASP.NET中伺服器端Session狀態的儲存
準備工作
為了您能更好的體驗到實驗現象,您可以建立一個叫做SessionState.aspx的頁面,然後把以下這些代碼添加到<body></body>中。
<scriptrunat="server">
Sub Session_Add(sender As Object, e As EventArgs)
Session("MySession") = text1.Value
span1.InnerHtml = "Session data updated! <P>Your session contains: <font color=red>" & \
Session("MySession").ToString() & "</font>"
End Sub
Sub CheckSession(sender As Object, eAs EventArgs)
If (Session("MySession")Is Nothing) Then
span1.InnerHtml = "NOTHING, SESSION DATA LOST!"
Else
span1.InnerHtml = "Your session contains: <font color=red>" & \
Session("MySession").ToString() & "</font>"
End If
End Sub
</script>
<formrunat="server"id="Form2">
<inputid="text1"type="text"runat="server"name="text1">
<inputtype="submit"runat="server"OnServerClick="Session_Add"
value="Add to Session State" id="Submit1"name="Submit1">
<inputtype="submit"runat="server"OnServerClick="CheckSession"
value="View Session State" id="Submit2"name="Submit2">
</form>
<hrsize="1">
<fontsize="6"><spanid="span1"runat="server" /></font>
這個SessionState.aspx的頁面可以用來測試在當前的伺服器上是否丟失了Session資訊。
將伺服器Session資訊儲存在進程中
讓我們來回到Web.config檔案的剛才那段段落中:
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>
當mode的值是InProc時,說明伺服器正在使用這種模式。