靜態變數和Session

FlyLolo發表於2017-04-21

靜態變數: Application級別的,不同客戶端訪問同一個變數。

Session:對於每個訪問的客戶端是獨立的,都有一個唯一的SessionID。也就是說,不同客戶端下,都可以有一個Session["SessionStr"],資料不互通

 

所以當使用靜態變數儲存一些資料的時候要考慮不同客戶端訪問的時候的安全問題。

 

舉例:  .net MVC

view:

    <p>SessionStr:@ViewBag.SessionStr</p>
    <p>StaticStr:@ViewBag.StaticStr</p>

    <form action="@Url.Action("test")" method="post">
        <input type="text" name="str" />
        <input type="submit" value="submit" />
    </form>

新建form, 用於輸入並提交一個字串。提交後將這個字串分別儲存至Session["SessionStr"]和 static string StaticStr

兩個P標籤, 分別用於顯示Session["SessionStr"]和 static string StaticStr的值。

下面是Controller中的簡單儲存邏輯:


        public static string StaticStr = "";


        [HttpPost]
        public ActionResult test(string str)
        {
            Session["SessionStr"] = str;
            StaticStr = str;


            return RedirectToAction("Index");
        }


        public ActionResult Index()
        {
            ViewBag.SessionStr = Session["SessionStr"] == null ? "": Session["SessionStr"].ToString();
            ViewBag.StaticStr = StaticStr;
            return View();
        }


IE頁面如下圖:

 

這兩個值都是空的。輸入hello提交,結果如下

 

 開啟另一個瀏覽器Firefox或者在另一臺電腦訪問該頁面

可見Static是application級別的, 但Session是不通的。

同樣在此頁面輸入world

兩個瀏覽器頁面中的StaticStr都會顯示為world。 但Session分別為hello 和world

 

相關文章