ASP.NET 狀態的傳遞和儲存

來源:互聯網
上載者:User

  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 xm lns="http://www.w3.org/1999/xhtml">

  <head>

  <me ta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title></title>

  </head>

  <body>

  <form>

  <in put type="submit" name="Read" value="讀取Cookie" /> 

  <in put 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 xm lns="http://www.w3.org/1999/xhtml">

  <head>

  <me ta 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>

  <in put type="text" name="UserName" value="$Model.LoginUser" /></td>

  </tr>

  <tr>

  <td>密碼</td>

  <td>

  <in put type="password" name="Password" /></td>

  </tr>

  <tr>

  <td>

  <in put 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 xm lns="http://www.w3.org/1999/xhtml">

  <head>

  <me ta 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>

  <in put type="text" name="txtUserName" /></td>

  </tr>

  <tr>

  <td>密碼</td>

  <td>

  <in put type="password" name="txtPassword" /></td>

  </tr>

  <tr>

  <td>

  <in put 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 xm lns="http://www.w3.org/1999/xhtml">

  <head>

  <me ta 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>

  <in put type="text" name="txtUserName" /></td>

  </tr>

  <tr>

  <td>密碼</td>

  <td>

  <in put type="password" name="txtPassword" /></td>

  </tr>

  <tr>

  <td>

  <in put 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是否存在

  ob ject 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自動銷毀了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.