標籤:
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