1,HTTP協議是無狀態的。服務器不會記住上次給瀏覽器的處理結果,如果需要上次處理結果(上次狀態)就需要瀏覽器把處理結果值(上次狀態)再次給服務器。
2,URL傳值:通過URL參數或者通過Form表單進行頁面件的傳值 (不能做到很自由的存取和讀取,而且不安全)
3,Cookie :①Cookie可以用來進行更加自由的數據的存取和讀取。
②Cookie是和站點相關的,自己域名寫的只有自己的域名才可以讀取。
③客戶端向服務器發送請求的時候 處理發送Form表單信息以外還會把和站點有關的所有的Cookie發送給服務器,是強制的。
④服務器返回的數據處理HTML數據以外,還會返回修改的Cookie,瀏覽器拿到修改后的Cookie更新到本地的Cookie
⑤服務器端使用Cookie案例,記住用戶名功能:
A,設置頁面值: Response.SetCookie(new HttpCookie("UserName",username))
B,讀取頁面值: username=Request.Cookies["UserName"].Value
⑥瀏覽器關閉以后Cookie的聲明周期到期,也就是Cookie的默認生命周期是瀏覽器的生命周期??梢酝ㄟ^設置Expires屬性設置Cookie的過期時間:Cookie.Expires=DateTime.Now.AddDays(-1)
⑦Cookie在客戶端是以鍵值對存在的
4,Cookie缺點:①客戶端額可以手動清楚Cookie 所以Cookie里面存放的信息是可有可無的信息
②瀏覽器對 Cookie 的大小有限制,因此只有不超過 4096 字節才能保證被接受
③機密信息不能放到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,建立對應的CookieTest.ashx頁面 實現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 判斷是點擊的那個按鈕 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最主要的一個功能是保存用戶的登陸名,這樣用戶在下次登陸的時候系統就可以自動填寫登陸名稱
A,新建LoginCookie.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="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, 新建對應的LoginCookie.ashx頁面,實現把用戶名讀取出來并寫入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 = "" }; //登陸賬號默認為空 //判斷Cookie是否存在,如果存在 把Cookie的值傳遞到HTML頁面,如果不存在就是默認的空 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的形式存放在客戶端,這樣每一次的請求就可以帶出用戶登陸名稱了
有一種情況: 用戶登陸成功以后就可以訪問網站的其他所有頁面,其他頁面就需要先判斷用戶是否登陸成功。
如果登陸成功為True放到Cookie中,這樣的客戶端就可以進行篡改把False改為True從而可以非法訪問為授權頁面了,這樣放到Cookie就不安全了。
如果登陸成功放到服務器端,那么網站的多個頁面就可以直接讀取到這個值,而且是安全的不會被客戶端篡改的了。
8,session原理: 把數據Value值存儲在服務器端并在客戶端存放Value對應的ID 。(ID,Value)都存放服務器 另外把ID以Cookie的形式存放客戶端。這樣就可以從客戶端Cookie中抓取ID,然后從服務器端讀取到ID對應的Value。
10,下面示例以Session原理實現頁面判斷用戶是否有成功登陸:成功登陸的用戶可以對特定頁面進行訪問、如果沒有成功登陸就跳轉到登陸頁面。
A. 添加類 SessionMgr.cs 在服務器端存儲 鍵值對 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>(); //設置鍵值對的值 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); } //返回服務器端ID對應的Value值 public static string GetValue(Guid id) { return KeyValue[id].ToString(); } }}
B. 添加 LoginSession.ashx 判斷用戶是否登陸成功,如果登陸成功把存儲對應的鍵值對的值
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") { //登陸成功,設置對應的鍵值對 Guid id = Guid.NewGuid(); // 產生唯一的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); //跳轉到授權頁面 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頁面,只有登陸后的賬戶才有權限訪問這個頁面
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對應的Value string strValue = SessionMgr.GetValue(id); //輸出Value值,并提示該賬號是已經登陸的賬號 context.Response.Write(strValue + ",您已經登陸本網站,有權限訪問此頁面"); } //如果Cookie不存在,則直接跳轉到登頁面 else { context.Response.Redirect("LoginSession.ashx"); } } public bool IsReusable { get { return false; } } }}
------------------------------------------------------------gif動畫演示----------------------------------------------------------------
11,上面的示例是也就是Session原理。asp.net已經內置了Session機制,下面我們直接用ASP.NET Session實現 判斷用戶是否有登陸成功:
(一般處理程序HttpHandler操作Session, 要實現IRequiresSessionState接口)
分別添加頁面: LoginSessionNew.ashx(登陸一般處理程序) , LoginSessionNew.html(登陸模板), AuthorizationPageNew.ashx(登陸后才有權限訪問的頁面)。
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; //跳轉到授權頁面 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(登陸后才有權限訪問的頁面)
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值,并提示該賬號是已經登陸的賬號 context.Response.Write(obj.ToString() + ",您已經登陸本網站,有權限訪問此頁面"); } //如果Session不存在,則直接跳轉到登頁面 else { context.Response.Redirect("LoginSessionNew.ashx"); } } public bool IsReusable { get { return false; } } }}
· ASP.NET內置Session機制同樣實現了對用戶是否登陸成功的判斷:LoginSessionNew.ashx頁面Headers中我們看到了Cookie中多了ASP.NET_SessionId
Session機制在客戶端存放了ASP.NET_SessionID
· 權限訪問頁面,請求頭中讀取到了客戶端Cookie中的ASP.NET_SessionID
12, ASP.NET的Session機制: Session依賴于Cookie , 借助Cookie在客戶端瀏覽器中記錄了ID, 在服務器端存儲了Value值。
13,Session的值是放到了服務器內存中,所以Session存放小數據。
Session(會話)有自動銷毀機制,如果一段時間內瀏覽器沒有和服務器交互,則Session會定時自動銷毀。
登陸賬號后,一段時間內如果不操作 系統就會自動退出,這就是Session自動銷毀了。
Demo 下載
新聞熱點
疑難解答