【.net基礎】--Application,Session,Cookie你能分的清嗎?

ZeroWM發表於2015-05-06

背景:

  每個東東產生的時候都是有原因滴,我個人覺得,這幾種方式跟快取很類似,都是把常用的一些資料放到快取裡面先存起來,比直接從記憶體或硬碟中讀取更加的迅速,從而提高效率。Application,Session,Cookie是Asp.Net中常用的三種存取臨時資料的方法。  (常用內建物件)


Application/session/Cookie對比:

對比

Session

Application

Cookie

作用

用於保護使用者的專用資訊

用於儲存所有使用者的公共資料資訊。

用於保護客戶瀏覽器請求伺服器頁面的請求資訊

使用

多人

全域性

單個

共享

No

Yes

No

有效期

個人退出20分鐘(可設),存資料效率低

程式週期,

會消失,考慮寫入檔案或資料庫

訪問過大會造成效能瓶頸

自定義,關閉瀏覽器會消失

資料

少,簡單,單個使用者,單個連結

任意

少,簡單,非敏感

位置

伺服器端

伺服器端

客戶端





登陸實戰演練:

        使用者登陸採用Cookie儲存使用者資訊,Session儲存使用者名稱,Application計算訪問量。整個業務邏輯是,使用者先進行登陸,登陸了之後進入一個新的頁面,顯示登陸的人數和登陸者的姓名。


login.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace demo5
{
    public partial class Login : System.Web.UI.Page
    {

        //登陸時點選登陸按鈕


        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //寫入cookie
            Response.Cookies["username1"].Value = txtUserName.Text;
            //設定cookie儲存時間
            Response.Cookies["username1"].Expires = DateTime.Now.AddDays(1);
            //判斷使用者名稱是否為空
            if (Request.Cookies["username1"] != null)
            {   //session獲取使用者名稱
                Session["username1"] = Request.Cookies["username1"].Value;
                //跳轉到歡迎頁面
                Response.Redirect("Welcome.aspx");
            }

        }



    }
}


login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="demo5.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    使用者名稱:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
        <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="登陸" />

    </div>
        
    </form>
    
</body>
</html>


結果頁面:


跳轉的新的頁面:

 Welcome.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace demo5
{
    public partial class Welcome : System.Web.UI.Page
    {

        //載入歡迎頁面
        protected void Page_Load(object sender, EventArgs e)
        {
            //如果session內部的使用者名稱為空
            if (Session["username1"] != null)
            {//列印字串內容
                string conent = "歡迎" + Session["username1"] + "進入ASP.NET";
                Response.Write(conent);
                //如果全域性變數不為空
                if (Application["SessionCount"] != null)
                {
                    labApplication.Text = Session["username1"] + "共登陸了" + Application["SessionCount"].ToString() + "次";
                }
            }
            
        }
       
    }
}

Welcome.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Welcome.aspx.cs" Inherits="demo5.Welcome" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="labApplication" runat="server" ></asp:Label>
    
    </div>
    </form>
</body>
</html>


global.asax

        protected void Application_Start(object sender, EventArgs e)
        {
           
            //全域性計數器 計數+1
            Application["SessionCount"] = 0;
            
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Session["username1"] = 0;
            //在新回話啟動時執行的程式碼
            Application.Lock();
            //全域性計數器 計數+1
            Application["SessionCount"] = (int)Application["SessionCount"] + 1;
            Application.UnLock();

        }


登陸成功頁:



現象分析:

1.如果登陸了之後,再開啟一個瀏覽器頁面,瀏覽同樣的網址,登陸次數會+1,說明Application在整個程式的生命週期中都起作用,而且可以被多個使用者訪問,儲存公共的使用者資料資訊.

2.有的時候,關閉了瀏覽器,立即重新啟動程式,使用者名稱仍然是之前的那個使用者名稱,證明Session是具有時效性的。


          

總結:

       做demo的時候並不是很順利,不過完成之後是很有成就感的,80分有的時候真的比100分實惠。



2015年7月16日補充:


Cookie的存入:

	//給定的使用者名稱建立身份驗證 Cookie
	 HttpCookie cookie = FormsAuthentication.GetAuthCookie(model.UserName, model.RememberMe);
	 cookie.Name = "selfUserInfo";
	 cookie.Expires = DateTime.Now.AddDays(1);
	 Response.Cookies.Add(cookie);

Cookie的取出:

  if (Request.Cookies["selfUserInfo"] != null)
	{
	      HttpCookie mycookie;
	      mycookie = Request.Cookies["selfUserInfo"];
	      Response.Cookies["selfUserInfo"].Expires = System.DateTime.Now.AddMonths(-1);//cookie過期處理
	      Response.Cookies.Remove("selfUserInfo");//清除 
	      Response.Cookies.Add(mycookie);//寫入立即過期的
	      Response.Cookies["selfUserInfo"].Expires = DateTime.Now.AddDays(-1);
	}
	//從cookie中返回使用者資訊

        var memberValidation = HttpContext.Request.Cookies.Get("selfUserInfo")

應用場景:

        .NET單點登入的時候,根據使用者名稱可以把使用者登入驗證產生的票據資訊存入Cookie中,也可以根據使用者名稱取出Cookie.


 


相關文章