ASP.NET MVC5總結(三)登陸中常用技術解析之session與cookie

來源:互聯網
上載者:User

標籤:

1.session機制

    session機制是在伺服器端保持狀態的方案,在做系統登陸時,我們往往會用到session來儲存一些使用者登入的重要訊息,而這些資訊是不能存在cookie中的。

    當訪問量增多時,是會比較佔用伺服器效能的。

寫session的方法

1 public static void WriteSession(string key, T value)2 {3 if (key.IsEmpty())4 return;5 HttpContext.Current.Session[key] = value;6 }
View Code

讀取session的方法

1 public static string GetSession(string key)2 {3        if (key.IsEmpty())4              return string.Empty;5         return HttpContext.Current.Session[key] as string;6 }
View Code

刪除指定的session的方法

1 public static void RemoveSession(string key)2         {3             if (key.IsEmpty())4                 return;5             HttpContext.Current.Session.Contents.Remove(key);6         }
View Code

2.cookie機制

   cookie機制採用的是在用戶端保持狀態的方案,在做系統登陸時,我們會將一下使用者的基本資料儲存到使用者的瀏覽器,這時候我們將用到cookie,不過它最大能存4K的資料。

寫cookie的方法

 1 public static void WriteCookie(string strName, string strValue) 2         { 3             HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; 4             if (cookie == null) 5             { 6                 cookie = new HttpCookie(strName); 7             } 8             cookie.Value = strValue; 9             HttpContext.Current.Response.AppendCookie(cookie);10         }
View Code

讀取cookie的方法

1 public static string GetCookie(string strName)2         {3             if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)4             {5                 return HttpContext.Current.Request.Cookies[strName].Value.ToString();6             }7             return "";8         }
View Code

刪除cookie的方法

1 public static void RemoveCookie(string CookiesName)2         {3             HttpCookie objCookie = new HttpCookie(CookiesName.Trim());4             objCookie.Expires = DateTime.Now.AddYears(-5);5             HttpContext.Current.Response.Cookies.Add(objCookie);6         }
View Code

 

ASP.NET MVC5總結(三)登陸中常用技術解析之session與cookie

聯繫我們

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