1,HTTP協(xié)議是無狀態(tài)的。服務(wù)器不會記住上次給瀏覽器的處理結(jié)果,如果需要上次處理結(jié)果(上次狀態(tài))就需要瀏覽器把處理結(jié)果值(上次狀態(tài))再次給服務(wù)器。
2,URL傳值:通過URL參數(shù)或者通過Form表單進(jìn)行頁面件的傳值 (不能做到很自由的存取和讀取,而且不安全)
3,Cookie :①Cookie可以用來進(jìn)行更加自由的數(shù)據(jù)的存取和讀取。
②Cookie是和站點(diǎn)相關(guān)的,自己域名寫的只有自己的域名才可以讀取。
③客戶端向服務(wù)器發(fā)送請求的時候 處理發(fā)送Form表單信息以外還會把和站點(diǎn)有關(guān)的所有的Cookie發(fā)送給服務(wù)器,是強(qiáng)制的。
④服務(wù)器返回的數(shù)據(jù)處理HTML數(shù)據(jù)以外,還會返回修改的Cookie,瀏覽器拿到修改后的Cookie更新到本地的Cookie
⑤服務(wù)器端使用Cookie案例,記住用戶名功能:
A,設(shè)置頁面值: Response.SetCookie(new HttpCookie("UserName",username))
B,讀取頁面值: username=Request.Cookies["UserName"].Value
⑥瀏覽器關(guān)閉以后Cookie的聲明周期到期,也就是Cookie的默認(rèn)生命周期是瀏覽器的生命周期??梢酝ㄟ^設(shè)置Expires屬性設(shè)置Cookie的過期時間:Cookie.Expires=DateTime.Now.AddDays(-1)
⑦Cookie在客戶端是以鍵值對存在的
4,Cookie缺點(diǎn):①客戶端額可以手動清楚Cookie 所以Cookie里面存放的信息是可有可無的信息
②瀏覽器對 Cookie 的大小有限制,因此只有不超過 4096 字節(jié)才能保證被接受
③機(jī)密信息不能放到Cookie里面
④Cookie不能跨瀏覽器
5,Cookie的寫和讀: A,新建CookieTest.html頁面并添加 兩個按鈕分別用于Cookie的讀和寫
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title></head><body> <form> <input type="submit" name="Read" value="讀取Cookie" /> <input type="submit" name="Write" value="寫入Cookie" /> <br /> 讀取出來的Cookie: $Model.CookieValue </form></body></html>
B,建立對應(yīng)的CookieTest.ashx頁面 實(shí)現(xiàn)Cookie的新建寫入本地以及讀取Cookie的值
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace HttpNoStatus{ /// <summary> /// HttpCookie 的摘要說明 /// </summary> public class CookieTest : IHttpHandler { public void PRocessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //if else 判斷是點(diǎn)擊的那個按鈕 if (!string.IsNullOrEmpty(context.Request["Read"])) { if (context.Request.Cookies["Age"] != null) { HttpCookie cookie = context.Request.Cookies["Age"]; string strValue = cookie.Value; var data = new { CookieValue = strValue }; //加載模板頁面并傳遞 Cookie Value的值 string strHtml = Common_Nvelocity.RenderHTML("CookieTest.html", data); context.Response.Write(strHtml); } else { context.Response.Write("cookie 不存在"); } } else if (!string.IsNullOrEmpty(context.Request["Write"])) { //寫入新的Cookie HttpCookie acookie = new HttpCookie("Age"); acookie.Value = "25"; acookie.Expires = DateTime.MaxValue; context.Response.Cookies.Add(acookie); //Cookie不存在 直接加載模板頁面 string strHtml = Common_Nvelocity.RenderHTML("CookieTest.html", null); context.Response.Write(strHtml); } else { //第一次加載頁面 string strHtml = Common_Nvelocity.RenderHTML("CookieTest.html", null); context.Response.Write(strHtml); } } public bool IsReusable { get { return false; } } }}
6,Cookie最主要的一個功能是保存用戶的登陸名,這樣用戶在下次登陸的時候系統(tǒng)就可以自動填寫登陸名稱
A,新建LoginCookie.html頁面,頁面中添加我們經(jīng)常見到的 用戶名,用戶密碼,登陸
登陸頁面第一次加載的時候,設(shè)置默認(rèn)的登陸名為空,登陸成功以及再次登陸的時候系統(tǒng)就自動補(bǔ)充登陸用戶名
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title></head><body> <form action="LoginCookie.ashx" method="post"> <table> <tr> <td>登陸名</td> <td> <input type="text" name="UserName" value="$Model.LoginUser" /></td> </tr> <tr> <td>密碼</td> <td> <input type="passWord" name="Password" /></td> </tr> <tr> <td> <input type="submit" name="Login" value="登陸" /></td> <td></td> </tr> </table> </form></body></html>
B, 新建對應(yīng)的LoginCookie.ashx頁面,實(shí)現(xiàn)把用戶名讀取出來并寫入Cookie "ckLoginUser"
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace HttpNoStatus{ /// <summary> /// LoginCookie 的摘要說明 /// </summary> public class LoginCookie : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //加載頁面直接顯示 頁面 if (context.Request.Form["Login"] == null) { string strHtml = ""; var data = new { LoginUser = "" }; //登陸賬號默認(rèn)為空 //判斷Cookie是否存在,如果存在 把Cookie的值傳遞到HTML頁面,如果不存在就是默認(rèn)的空 if (context.Request.Cookies["ckLoginUser"] != null) { data = new { LoginUser = context.Request.Cookies["ckLoginUser"].Value.ToString() }; } strHtml = Common_Nvelocity.RenderHTML("LoginCookie.html", data); context.Response.Write(strHtml); } else { //用戶登陸,保存用戶名到Cookie HttpCookie LoginUser = new HttpCookie("ckLoginUser"); LoginUser.Value = context.Request.Form["UserName"]; LoginUser.Expires = DateTime.Now.AddDays(30); context.Response.Cookies.Add(LoginUser); //加載頁面直接顯示 頁面 string strHtml = Common_Nvelocity.RenderHTML("LoginCookie.html", new { LoginUser = context.Request.Form["UserName"] }); context.Response.Write(strHtml); } } public bool IsReusable { get { return false; } } }}
7,以上方法把登陸賬號以Cookie的形式存放在客戶端,這樣每一次的請求就可以帶出用戶登陸名稱了
有一種情況: 用戶登陸成功以后就可以訪問網(wǎng)站的其他所有頁面,其他頁面就需要先判斷用戶是否登陸成功。
如果登陸成功為True放到Cookie中,這樣的客戶端就可以進(jìn)行篡改把False改為True從而可以非法訪問為授權(quán)頁面了,這樣放到Cookie就不安全了。
如果登陸成功放到服務(wù)器端,那么網(wǎng)站的多個頁面就可以直接讀取到這個值,而且是安全的不會被客戶端篡改的了。
8,session原理: 把數(shù)據(jù)Value值存儲在服務(wù)器端并在客戶端存放Value對應(yīng)的ID 。(ID,Value)都存放服務(wù)器 另外把ID以Cookie的形式存放客戶端。這樣就可以從客戶端Cookie中抓取ID,然后從服務(wù)器端讀取到ID對應(yīng)的Value。
10,下面示例以Session原理實(shí)現(xiàn)頁面判斷用戶是否有成功登陸:成功登陸的用戶可以對特定頁面進(jìn)行訪問、如果沒有成功登陸就跳轉(zhuǎn)到登陸頁面。
A. 添加類 SessionMgr.cs 在服務(wù)器端存儲 鍵值對 ID/Value
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace HttpNoStatus{ public class SessionMgr { //定義鍵值對,存儲登陸信息 private static Dictionary<Guid, string> KeyValue = new Dictionary<Guid, string>(); //設(shè)置鍵值對的值 public static void SetKeyValue(Guid id, string value) { KeyValue[id] = value; } /// <summary> /// 檢查客戶端傳遞過來的鍵值對是否存在 /// </summary> /// <param name="id"></param> /// <returns></returns> public static bool IfIdExist(Guid id) { return KeyValue.Keys.Contains(id); } //返回服務(wù)器端ID對應(yīng)的Value值 public static string GetValue(Guid id) { return KeyValue[id].ToString(); } }}
B. 添加 LoginSession.ashx 判斷用戶是否登陸成功,如果登陸成功把存儲對應(yīng)的鍵值對的值
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace HttpNoStatus{ /// <summary> /// LoginSession 的摘要說明 /// </summary> public class LoginSession : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string strHtml = ""; //讀取用戶名和密碼 string strUserName = context.Request.Form["txtUserName"]; string strPwd = context.Request.Form["txtPassword"]; if (strPwd == "123456") { //登陸成功,設(shè)置對應(yīng)的鍵值對 Guid id = Guid.NewGuid(); // 產(chǎn)生唯一的ID SessionMgr.SetKeyValue(id, strUserName); //id 保存在客戶端cookie中 HttpCookie loginCookie = new HttpCookie("LoginCookie"); loginCookie.Value = id.ToString(); loginCookie.Expires = DateTime.Now.AddDays(7); context.Response.Cookies.Add(loginCookie); //跳轉(zhuǎn)到授權(quán)頁面 context.Response.Redirect("AuthorizationPage.ashx"); } else { //登陸失敗 , 加載登陸頁面 strHtml = Common_Nvelocity.RenderHTML("LoginSession.html", null); context.Response.Write(strHtml); } } public bool IsReusable { get { return false; } } }}
C. Templates文件夾下添加LoginSession.html 登陸頁面
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title></head><body> <form action="LoginSession.ashx" method="post"> <table> <tr> <td>登陸名</td> <td> <input type="text" name="txtUserName" /></td> </tr> <tr> <td>密碼</td> <td> <input type="password" name="txtPassword" /></td> </tr> <tr> <td> <input type="submit" name="Login" value="登陸" /></td> <td></td> </tr> </table> </form></body></html>
D. 添加AuthorizationPage.ashx頁面,只有登陸后的賬戶才有權(quán)限訪問這個頁面
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace HttpNoStatus.Templates{ /// <summary> /// AuthorizationPage 的摘要說明 /// </summary> public class AuthorizationPage : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //抓取客戶端 Cookie的ID值 HttpCookie loginCookie = context.Request.Cookies["LoginCookie"]; if (loginCookie != null) { Guid id = new Guid(loginCookie.Value); // 讀取id對應(yīng)的Value string strValue = SessionMgr.GetValue(id); //輸出Value值,并提示該賬號是已經(jīng)登陸的賬號 context.Response.Write(strValue + ",您已經(jīng)登陸本網(wǎng)站,有權(quán)限訪問此頁面"); } //如果Cookie不存在,則直接跳轉(zhuǎn)到登頁面 else { context.Response.Redirect("LoginSession.ashx"); } } public bool IsReusable { get { return false; } } }}
------------------------------------------------------------gif動畫演示----------------------------------------------------------------
11,上面的示例是也就是Session原理。asp.net已經(jīng)內(nèi)置了Session機(jī)制,下面我們直接用ASP.NET Session實(shí)現(xiàn) 判斷用戶是否有登陸成功:
(一般處理程序HttpHandler操作Session, 要實(shí)現(xiàn)IRequiresSessionState接口)
分別添加頁面: LoginSessionNew.ashx(登陸一般處理程序) , LoginSessionNew.html(登陸模板), AuthorizationPageNew.ashx(登陸后才有權(quán)限訪問的頁面)。
A,LoginSessionNew.ashx(登陸一般處理程序)
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.SessionState;namespace HttpNoStatus{ /// <summary> /// LoginSessionNew 的摘要說明 /// </summary> public class LoginSessionNew : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string strHtml = ""; //讀取用戶名和密碼 string strUserName = context.Request.Form["txtUserName"]; string strPwd = context.Request.Form["txtPassword"]; if (strPwd == "123456") { //登陸成功,直接保存Session值 context.Session["LoginUserName"] = strUserName; //跳轉(zhuǎn)到授權(quán)頁面 context.Response.Redirect("AuthorizationPageNew.ashx"); } else { //登陸失敗 , 加載登陸頁面 strHtml = Common_Nvelocity.RenderHTML("LoginSessionNew.html", null); context.Response.Write(strHtml); } } public bool IsReusable { get { return false; } } }}
B,Templates模板下新建LoginSessionNew.html(登陸模板)
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title></head><body> <form action="LoginSessionNew.ashx" method="post"> <table> <tr> <td>登陸名</td> <td> <input type="text" name="txtUserName" /></td> </tr> <tr> <td>密碼</td> <td> <input type="password" name="txtPassword" /></td> </tr> <tr> <td> <input type="submit" name="Login" value="登陸" /></td> <td></td> </tr> </table> </form></body></html>
C,AuthorizationPageNew.ashx(登陸后才有權(quán)限訪問的頁面)
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.SessionState;namespace HttpNoStatus{ /// <summary> /// AuthorizationPageNew 的摘要說明 /// </summary> public class AuthorizationPageNew : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //檢查Session是否存在 object obj = context.Session["LoginUserName"]; if (obj != null) { //Session存在,讀取Session值,并提示該賬號是已經(jīng)登陸的賬號 context.Response.Write(obj.ToString() + ",您已經(jīng)登陸本網(wǎng)站,有權(quán)限訪問此頁面"); } //如果Session不存在,則直接跳轉(zhuǎn)到登頁面 else { context.Response.Redirect("LoginSessionNew.ashx"); } } public bool IsReusable { get { return false; } } }}
· ASP.NET內(nèi)置Session機(jī)制同樣實(shí)現(xiàn)了對用戶是否登陸成功的判斷:LoginSessionNew.ashx頁面Headers中我們看到了Cookie中多了ASP.NET_SessionId
Session機(jī)制在客戶端存放了ASP.NET_SessionID
· 權(quán)限訪問頁面,請求頭中讀取到了客戶端Cookie中的ASP.NET_SessionID
12, ASP.NET的Session機(jī)制: Session依賴于Cookie , 借助Cookie在客戶端瀏覽器中記錄了ID, 在服務(wù)器端存儲了Value值。
13,Session的值是放到了服務(wù)器內(nèi)存中,所以Session存放小數(shù)據(jù)。
Session(會話)有自動銷毀機(jī)制,如果一段時間內(nèi)瀏覽器沒有和服務(wù)器交互,則Session會定時自動銷毀。
登陸賬號后,一段時間內(nèi)如果不操作 系統(tǒng)就會自動退出,這就是Session自動銷毀了。
Demo 下載
新聞熱點(diǎn)
疑難解答
圖片精選