(華版)
很多人都會在地一時間裡想到用Cookies(HttpCookies)來儲存某些資料;以便在遊覽到另一個WebForm時,依然能夠從使用者端讀取所儲存的資料。但是,萬一如果使用者的遊覽器不容許Cookies。。。那就不是完了嗎。。。更何況Cookies只能容納4K Byte的資料而且!
Dim DemoCookie As New HttpCookie("sampleCookie")
Dim time As DateTime = DateTime.Now
DemoCookie.Values.Add("Time", time.ToString())
DemoCookie.Expires = time.AddDays(5)
Response.Cookies.Add(DemoCookie)
Response.Redirect("sample.aspx")
所以就要改用server side的SQL資料庫方式而放棄client side的Cookies;更何況用SQL資料庫是非常簡單,只需安裝.NET Framework所提供的InstallSqlState.sql script和修改一下Web.Config檔案就行了。其它就如平常寫Session變數一模一樣。
InstallSqlState.sql可以在 C:\WINDOWS\Microsoft.NET\Framework\(版本號碼)\ 檔案夾裡找到。
以下就是需要修改的Web.Config裡的sessionState屬性:
<sessionState
mode="SQLServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=localhost; integrated security=true"
cookieless="false"
timeout="20"
/>
把原有的
1. mode=InProc改去mode=SQLServer。
2. 修改sqlConnectionString字串,但是在這裡不用填寫Initial Catalog。因為AspState是默人Catalog,
也就InstallSqlState.sql所安裝的ASP State Management database。
3. 把timeout修改去你想要的session expire值;timeout的單位以分鐘來計算。
4. cookieless="false"代表SesionID容納在URL裡,比如http://server/(SessionID)/Sample.aspx
所以,此屬性的值一般都是false。
Dim time As DateTime = DateTime.Now
Session("Time") = time.ToString())