Lập trình viên quốc tế ACCP
Lập trình viên Java
Kiểm thử phần mền itester
Lập trình viên PHP

Sử dụng Cookie trong ASP.NET – Tự học lập trình ASP

asp1803 Sử dụng Cookie trong ASP.NET   Tự học lập trình ASPBài viết này sẻ hướng dẩn làm một ví dụ nhỏ về Cookie để hiểu được cách thức làm việc của Cookie – Cookie là một file được tạo ra từng web site mà bạn viếng thăm , nó chứa thông tin của bạn trên máy tin của bạn .

Code:

(cookie.aspx)

<script runat="server">
// sử lý dự kiện click nút đăng nhập
protected void bt_login_click(Object Src, EventArgs E)
{
if(tb_username.Text != ""){

// khai báo biến cookie
HttpCookie cookie_username = new HttpCookie("username",tb_username.Text);

// Gán thời gian sống của Cookie là 30 ngày
cookie_username.Expires = DateTime.Now.AddDays(30);

// Thêm Cookie
Response.Cookies.Add(cookie_username);

// làm tươi Response.Redirect("cookie.aspx");
}
}
// sử lý dự kiện click nút Xóa Cookie
protected void bt_delete_click(Object Src, EventArgs E)
{
// khai báo biến cookie
HttpCookie cookie_username = new HttpCookie("username","");
// Gán thời gian sống của Cookie là thời gian hiện tại
cookie_username.Expires = DateTime.Now;
// Thêm Cookie
Response.Cookies.Add(cookie_username);
// làm tươi
Response.Redirect("cookie.aspx");
}
</script>
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post" name="form1" runat="server" id="form1">
<!–Kiểm tra nếu biến Cookie username tồn tại thì đăng nhập–>
<%if(Request.Cookies["username"] == null){%>
Tên đăng nhập
<asp:TextBox ID="tb_username" runat="server" />
<asp:Button ID="bt_login" runat="server" OnClick="bt_login_click" Text="Đăng nhập" />
<!–Ngược lại thì hiển thị tên đăng nhập–>
<%}else{%>
Chào, <%=Request.Cookies["username"].Value%>
<asp:Button ID="bt_delete" runat="server" OnClick="bt_delete_click" Text="Xóa Cookie" />
<%}%>
</form>
</body>
</html>

Theo thegioiweb

Bạn đang muốn nâng cao kỹ năng lập trình của mình ?


Bài viết liên quan:

  1. Khái niệm cơ bản về Cookie và session trong PHP
  2. Bảo mật Database trong lập trình PHP
  3. Khắc phục sự cố trong quá trình gỡ bỏ các ứng dụng
  4. Đoạn code dùng để gửi mail bằng ASP.NET
  5. Bài 10: Các ứng dụng trong ngôn ngữ lập trình Java
  6. Các thẻ trong ASP – Ngôn ngữ lập trình ASP
  7. Bảo mật website trong lập trình PHP
  8. Bảo mật Session trong lập trình PHP