(+84) 236.3827111 ex. 402

Trong ASP.NET, Session và Cookie khác nhau ở điểm nào?


Trong ASP.NET, SessionCookie đều dùng để lưu trữ thông tin người dùng nhưng khác nhau ở nơi lưu trữ và mức độ bảo mật.

Session

  • Lưu dữ liệu trên Server
  • Bảo mật cao hơn
  • Thường dùng cho: đăng nhập, giỏ hàng, quyền người dùng

Ví dụ:

Session["user"] = "admin";

Lấy dữ liệu:

string user = Session["user"].ToString();

Cookie

  • Lưu dữ liệu trên trình duyệt (Client)
  • Tồn tại lâu hơn
  • Thường dùng cho: Remember Me, lưu ngôn ngữ, giao diện

Ví dụ:

HttpCookie ck = new HttpCookie("user"); ck.Value = "admin"; ck.Expires = DateTime.Now.AddDays(7); Response.Cookies.Add(ck);
Đọc Cookie:
string user = Request.Cookies["user"].Value;