如何用ASP.NET裡的State Management Database來儲存Session Variable。

來源:互聯網
上載者:User

(華版)

很多人都會在地一時間裡想到用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())

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.