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

1.session機制瀏覽器

    session機制是在服務器端保持狀態的方案,在作系統登錄時,咱們每每會用到session來存儲一些用戶登陸的重要信息,而這些信息是不能存在cookie中的。服務器

    當訪問量增多時,是會比較佔用服務器性能的。cookie

寫session的方法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的方法ide

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機制spa

   cookie機制採用的是在客戶端保持狀態的方案,在作系統登錄時,咱們會將一下用戶的基本信息存儲到用戶的瀏覽器,這時候咱們將用到cookie,不過它最大能存4K的數據。code

寫cookie的方法blog

 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的方法string

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
相關文章
相關標籤/搜索